Os.path.split, changing the file name without compromising the path

I followed Python to get the file name and change it and save it in a variable . which work great and change the file name as needed.

but now I am faced with the problem of the path in which the file is saved. since the file is saved in " media / ok_abc.txt ", whereas it should be media / documents / ok_abc.txt

eg.

docfile = / media / documents / abc.csv after applying the below statement

filename = os.path.splitext(docfile.name)[0]
newfilename = 'ok_%s.txt' % filename

I can change the file name, but the path decreases as /media/ok_abc.txt , it should be /media/documents/abc.txt

how can I change the file name without compromising on the way

+4
1

, .

path, filename = os.path.split(docfile)
filename = os.path.splitext(filename)[0]
newfilename = 'ok_%s.txt' % filename
newpath = os.path.join(path, newfilename)
+12

All Articles