i have followed Python get file name and change & save it in variable. which work fine and change the file name as required.
but now i am facing problem with path where the file is getting saved. as the file is getting saved in "media/ok_abc.txt" whereas it should be media/documents/ok_abc.txt
e.g.
docfile = /media/documents/abc.csv after applaying below instruction
filename = os.path.splitext(docfile.name)[0]
newfilename = 'ok_%s.txt' % filename
am able to change the file name but the path is getting reduced as /media/ok_abc.txt, it should be /media/documents/abc.txt
how i can change the file name with out compromising on the Path
To get the file name from the path, use the os. path. basename() method. Working with UNIX or MacOS uses the slash / as path separator, and Windows uses the backslash \ as the separator.
# os.path.split() function. # will return empty. # head and tail if. # specified path is empty.
The os. path. split() function accepts a path-like object representing a file system path. A path-like object is either an str or bytes object representing a path.
How do you change the file path name? When you go to any file or directory and right click and press rename. You can rename it and then move on.
Extract the directory from the full file path, and later add it back.
path, filename = os.path.split(docfile)
filename = os.path.splitext(filename)[0]
newfilename = 'ok_%s.txt' % filename
newpath = os.path.join(path, newfilename)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With