9

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

Community
  • 1
  • 1
ashir nasir
  • 207
  • 2
  • 6
  • 11

1 Answers1

22

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)
ledzep2
  • 801
  • 7
  • 12