Move all files from a directory to another directory in Python
This post will discuss how to move all files from a directory to another directory in Python.
1. Using shutil.move() function
You can use the shutil module to move files within the same or different file systems. To move a file, shutil has the move() function. It calls the os.rename() function when the destination is on the same disk as the source; otherwise, it copies the source file to the destination and then deletes it.
|
1 2 3 4 5 6 7 8 9 10 11 |
import shutil import os src = '/path/to/src/dir' dest = '/path/to/dest/dir' files = os.listdir(src) for f in files: shutil.move(src + f, dest) |
2. Using os.rename() function
Another solution is to use the os.rename() function for moving all files from a directory to another directory within a file system. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 |
import os src = '/path/to/src/dir' dest = '/path/to/dest/dir' files = os.listdir(src) for f in files: os.rename(src + f, dest + f) |
The os.rename() can be used when the destination is on the same disk as the source. However, it raises an exception when the file already exists in the destination. If you want to overwrite the destination file, use os.replace().
|
1 2 3 4 5 6 7 8 9 10 |
import os src = '/path/to/src/dir' dest = '/path/to/dest/dir' files = os.listdir(src) for f in files: os.replace(src + f, dest + f) |
That’s all about moving all files from a directory to another directory 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 :)