Summary: In this tutorial, you’ll learn how to rename a file in Python using the rename()
function of the os
module.
To rename a file in Python, you use the rename()
function from the os
module.
Here’s the basic syntax of the rename() function:
os.rename(src, dst)
Code language: CSS (css)
The rename function renames the src
to dst
.
If the src
file does not exist, the rename()
function raises a FileNotFound
error. Likewise, if the dst
already exists, the rename()
function issues a FileExistsError
error.
For example, the following uses the rename()
function to rename the file readme.txt
to notes.txt
:
import os
os.rename('readme.txt', 'notes.txt')
Code language: JavaScript (javascript)
To avoid an error if the readme.txt
doesn’t exist and/or the notes.txt
file already exists, you can use the try...except
statement:
import os
try:
os.rename('readme.txt', 'notes.txt')
except FileNotFoundError as e:
print(e)
except FileExistsError as e:
print(e)
Code language: Python (python)
The following shows the output when the readme.txt
file does not exist:
[WinError 2] The system cannot find the file specified: 'readme.txt' -> 'notes.txt'
Code language: JavaScript (javascript)
The following shows the output if the notes.txt
already exists:
[WinError 183] Cannot create a file when that file already exists: 'readme.txt' -> 'notes.txt'
Code language: JavaScript (javascript)
Summary #
- Use the
os.rename()
function to rename a file.