How to Rename a File or Folder in Python 


               


How to Rename a File or Folder in Python



Python


In this article, we show how to rename a file or folder in Python.

In Python, it is relatively simple to rename a file or a folder.

We'll first go over how to rename a file. Then, we'll go over how to rename a folder.


How to Rename a File

The code to rename a file in Python is shown below.



So, first, we must import the os module.

So, the code above renames the file, file.txt, to file2.txt.

It's very simple. All you have to do is use the os.rename() function. Inside of this function, you place the original file you want to rename as the first parameter and, as the second parameter, you put the name you want that file renamed to.


How to Rename a Folder

Renaming a folder is the same exact process as renaming a file. We use the os.rename() function to rename a folder.



So, the code above changes the folder, PythonProjects, to PythonPortfolio.

Related Resources



HTML Comment Box is loading comments...