Rename Files Using Python
I want to rename a file from say {file1} to {file2}. I read about os.rename(file1,file2) in python and is able to do so. I succeeded only when the the file is placed in the same fo
Solution 1:
Just use the full path, instead of the relative path:
oldFile = 'C:\\folder\\subfolder\\inFile.txt'
newFile = 'C:\\foo\\bar\\somewhere\\other\\outFile.txt'
os.rename(oldFile, newFile)
To get the double-slash behavior, you can do the following
import os
oldFile = r'C:\folder\subfolder\inFile.txt' # note the r character for raw string
os.path.normpath(oldFile)
Output
'C:\\folder\\subfolder\\inFile.txt'
Solution 2:
As others have noted, you need to use full path.
On the other note, take a look at shutil.move documentation, it can also be used for renaming.
Post a Comment for "Rename Files Using Python"