snippetpythonCriticalCanonical
How do I move a file in Python?
Viewed 0 times
movehowfilepython
Problem
How can I do the equivalent of
mv in Python?mv "path/to/current/file.foo" "path/to/new/destination/for/file.foo"
Solution
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")- The filename (
"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.
- The directory within which the new file is being created must already exist.
- On Windows, a file with that name must not exist or an exception will be raised, but
os.replace()will silently replace a file even in that occurrence.
shutil.movesimply callsos.renamein most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.
Code Snippets
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")Context
Stack Overflow Q#8858008, score: 2292
Revisions (0)
No revisions yet.