Summary: in this tutorial, you’ll learn how to rename a file using the os.rename()
function.
To rename a file, you use the os.rename()
function:
os.rename(src,dst)
Code language: CSS (css)
If the src
file does not exist, the os.rename()
function raises a FileNotFound
error. Similarly, if the dst
already exists, the os.rename()
function issues a FileExistsError
error.
For example, the following uses the os.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: PHP (php)
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)
And 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.
Did you find this tutorial helpful ?