1

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.

2
  • 1
    you need use full path. Commented Aug 16, 2014 at 17:36
  • note: there is also os.replace, os.renames functions. Commented Aug 16, 2014 at 17:58

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

7 Comments

Actually I tried this, and on my system it didn't work, what worked is using \\ instead of \.
@AkashdeepSaluja Maybe you needed to escape the backslashes.
Yes you are correct, you need double backslashes, that was my mistake.
If you know, can you please edit the answer with the function used to convert \ to \\.
Please see my most recent edit. This uses the os.path.normpath function to create a path.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.