How to move a file in Python? How to move a file in Python? python python

How to move a file in Python?


os.rename(), os.replace(), or shutil.move()

All employ the same syntax:

import osimport shutilos.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")

Note that you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.

Note also that in the first two cases the directory in 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.

As has been noted in comments on other answers, 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.


Although os.rename() and shutil.move() will both rename files, the command that is closest to the Unix mv command is shutil.move(). The difference is that os.rename() doesn't work if the source and destination are on different disks, while shutil.move() doesn't care what disk the files are on.


After Python 3.4, you can also use pathlib's class Path to move file.

from pathlib import PathPath("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename


matomo