Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a file in Python?

I looked into the Python os interface, but was unable to locate a method to move a file. How would I do the equivalent of $ mv ... in Python?

>>> source_files = '/PATH/TO/FOLDER/*' >>> destination_folder = 'PATH/TO/FOLDER' >>> # equivalent of $ mv source_files destination_folder 
like image 984
David542 Avatar asked Jan 13 '12 22:01

David542


People also ask

What is move () in Python?

The Python shutil. move() method moves a file to another location on your computer. This method is part of the shutil model, which you must import before using this method. Moving files is a common operation in Python programs.


2 Answers

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() is files disk agnostic.

like image 22
Jim Calfas Avatar answered Oct 03 '22 08:10

Jim Calfas


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") 

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.

like image 190
ig0774 Avatar answered Oct 03 '22 07:10

ig0774