Skip to content
Home » How to Rename or Move Files in Python

How to Rename or Move Files in Python

Spread the love

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version:


Spread the love

Leave a Reply