Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.split, changing file name with out compromising the Path

Tags:

python

django

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

like image 761
ashir nasir Avatar asked Sep 23 '13 01:09

ashir nasir


People also ask

How do I separate filenames from 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.

What does os path split return?

# os.path.split() function. # will return empty. # head and tail if. # specified path is empty.

What does calling os path split () do?

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 a filename in 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.


1 Answers

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)
like image 152
ledzep2 Avatar answered Oct 21 '22 07:10

ledzep2