Rename a file in Python
This post will discuss how to rename a file in Python.
1. Using os.rename() function
A simple solution to rename a file in Python is using the os.rename() function.
|
1 2 3 |
import os os.rename('filename.txt', 'new_filename.txt') |
If the file is not present in the working directory, you need to specify its full path.
|
1 2 3 |
import os os.rename('/path/to/dir/filename.txt', '/path/to/dir/new_filename.txt') |
If the source and destination directory are the same, i.e., you can do like:
|
1 2 3 4 5 6 7 8 |
import os dir = '/path/to/dir' old_file = os.path.join(dir, 'filename.txt') new_file = os.path.join(dir, 'new_filename.txt') os.rename(old_file, new_file) |
2. Using shutil.move() function
Alternatively, you can use the shutil module, which offers several high-level operations on files. You can use the shutil.move() function to rename or move a file.
|
1 2 3 |
import shutil shutil.move('/path/to/dir/filename.txt', '/path/to/dir/new_filename.txt') |
That’s all about renaming a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)