How can I do the equivalent of mv
in Python?
mv "path/to/current/file.foo" "path/to/new/destination/for/file.foo"
os.rename()
, os.replace()
, or shutil.move()
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")
"file.foo"
) must be included in both the source and destination arguments. If it differs between the two, the file will be renamed as well as moved.os.replace()
will silently replace a file even in that occurrence.shutil.move
simply calls os.rename
in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.