Move a file in Python
This post will discuss how to move a file in Python.
1. Using os.rename() function
A simple solution to move a Python file is using the os.rename() function.
|
1 2 3 4 5 6 7 |
import os src = '/path/to/src/dir/filename.txt' dest = '/path/to/dest/dir/filename.txt' os.rename(src, dest) |
2. Using os.replace() function
The os.rename() function raises an exception when destination file already exist. If you want to overwrite the destination file, use os.replace().
|
1 2 3 4 5 6 7 |
import os src = '/path/to/src/dir/filename.txt' dest = '/path/to/dest/dir/filename.txt' os.replace(src, dest) |
3. Using shutil.move() function
Alternatively, you can use the shutil module, which offers several high-level operations on files. To move a file, shutil.move() function can be used.
|
1 2 3 |
import shutil shutil.move('/path/to/src/dir/filename.txt', '/path/to/dest/dir/filename.txt') |
Note that os.rename() doesn’t work if the destination file is on a different file system. The shutil.move() calls os.rename() when the destination is on the current file system. Otherwise, it will copy the source file to the destination location and then delete the source file.
That’s all about moving 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 :)