Python – Rename File
To rename file in Python, import os library, call os.rename() function, and pass the old file path and new file path as arguments.
The syntax to call os.rename() function to rename a file is
import os os.rename('source', 'destination')
The path to the file should also be included in the file name.
In the following program, we will rename the file “sample_1.txt” to “sample_2.txt”.
import os old_file_name = "myfolder/sample_1.txt" new_file_name = "myfolder/sample_2.txt" try : os.rename(old_file_name, new_file_name) print('File renamed successfully.') except: print('Could not rename file.') print('An exception occurred.')
File renamed successfully.
In this tutorial of Python Examples, we learned how to rename a file using os.rename() function, with the help of examples.