Reputation: 3089
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 folder as python script, so I want to ask how can we rename files of other folders i.e. different folder than the one in which python script is placed.
Upvotes: 1
Views: 574
Reputation: 3654
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.
Upvotes: 0
Reputation: 118021
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'
Upvotes: 1