How can I move files in Python? mv “path/to/current/file.foo” “path/to/new/destination/for/file.foo”
Hello Apksha,
All employ the same syntax:
import os
import shutil
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
The filename (“file.foo”) must be included in both the source and destination arguments. If the filename differs between the two, the file will be renamed as well as moved. The directory where the new file is being created must already exist.
On Windows:
-
os.rename()
andshutil.move()
will raise an exception if a file with that name already exists. -
os.replace()
will silently replace an existing file.
shutil.move
generally calls os.rename
, but if the destination is on a different disk than the source, it will copy the file and then delete the source file.
Hello Apksha,
Am I the only one who thinks os.rename
doesn’t work for directories? As quoted: “If dst
is a directory, OSError
will be raised.”
Although os.rename()
and shutil.move()
can both rename files, shutil.move()
is the closest to the Unix mv
command. The key difference is that os.rename()
fails if the source and destination are on different disks, whereas shutil.move()
is disk-agnostic.
Hello Apksha,
Starting with Python 3.4, you can use the Path
class from the pathlib
module to move a file:
from pathlib import Path
Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")