How to move a file in Python using shutil.move()?
Published on Aug. 22, 2023, 12:17 p.m.
To move a file in Python, you can use the shutil.move()
method from the shutil
library. This method takes two parameters: the source file path and the destination file path. Here is an example:
import shutil
src = "/path/to/file.txt"
dst = "/path/to/newlocation/file.txt"
shutil.move(src, dst)
This example moves the file located at /path/to/file.txt
to /path/to/newlocation/file.txt
.
One benefit of using shutil.move()
over os.rename()
is that shutil.move()
can handle cases where the source and destination files are on different filesystems, whereas os.rename()
cannot. Additionally, shutil.move()
allows you to specify a new filename for the file being moved, whereas os.rename()
only allows you to change the path.
Note that if the destination file already exists, shutil.move()
will overwrite it without warning. Also, if an exception occurs during the move operation, the source file may be left in an inconsistent state.
Using shutil.move()
is useful when you need to move a file from one location to another in your file system.