Today we’ll see how to rename and move files in Python. Actually, it’s the same thing.
First, let’s create a new folder and name it folderA. Inside folderA let’s create another empty folder and let’s name it folderB. Let’s also create a text file in folderA and name it file1.txt.
What we need is the rename function in the os module, so let’s import the module:
import os
Now we want to rename file1.txt to newfile.txt. We need the old name (along with the full path if the file is in a different folder than the current folder) and the new name:
old = r'C:\Users\user-1\Desktop\folderA\file1.txt'
new = r'C:\Users\user-1\Desktop\folderA\newfile.txt'
Now we can use the rename method:
os.rename(old, new)
Next let’s change the extension from .txt to .docx:
old = r'C:\Users\user-1\Desktop\folderA\newfile.txt'
new = r'C:\Users\user-1\Desktop\folderA\newfile.docx'
os.rename(old, new)
The .docx extension is used by Microsoft Word, so now we can open the file in Microsoft Word.
Finally, let’s move the file to folderB. How to we move files? Moving a file to a folder is actually renaming the file so that the new path contains the folder we want to move the file to:
old = r'C:\Users\user-1\Desktop\folderA\newfile.docx'
new = r'C:\Users\user-1\Desktop\folderA\folderB\newfile.docx'
os.rename(old, new)
As you can see, moving and renaming files is pretty simple.
Here’s the video version: