python script - How to move a file in Python

5 Answers

os.rename() or shutil.move()

Both employ the same syntax:

import os
import shutil

os.rename("path/to/current/", "path/to/new/destination/for/")
shutil.move("path/to/current/", "path/to/new/destination/for/")

Note that in both cases the directory in which the new file is being created must already exist, (but, on Windows, a file with that name must not exist or an exception will be raised). Note also, you must include the file name ( in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.

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.

and rename

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

For either the os.rename or shutil.move you will need to import the module. No * character is necessary to get all the files moved.

We have a folder at /opt/awesome called source with one file named awesome.txt.

in /opt/awesome
○ → ls
○ → ls source

>>> source = '/opt/awesome/source'
>>> destination = '/opt/awesome/destination'
>>> import os
>>> os.rename(source, destination)
>>> os.listdir('/opt/awesome')

We used os.listdir to see that the folder name in fact changed. Here's the shutil moving the destination back to source.

>>> import shutil
>>> shutil.move(destination, source)
>>> os.listdir('/opt/awesome/source')

This time I checked inside the source folder to be sure the awesome.txt file I created exists. It is there :)

Now we have moved a folder and its files from a source to a destination and back again.

This is what I'm using at the moment:

import os, shutil
path = "/volume1/Users/Transfer/"
moveto = "/volume1/Users/Drive_Transfer/"
files = os.listdir(path)
for f in files:
    src = path+f
    dst = moveto+f

Now fully functional. Hope this helps you.

This is solution, which does not enables shell using mv.

import subprocess

source      = 'pathToCurrent/'
destination = 'pathToNew/'

p = subprocess.Popen(['mv', source, destination], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
res = p.communicate()[0].decode('utf-8').strip()

if p.returncode:
    print 'ERROR: ' + res

Based on the answer described here, using subprocess is another option.

Something like this:"mv %s %s" % (source_files, destination_folder), shell=True)

I am curious to know the pro's and con's of this method compared to shutil. Since in my case I am already using subprocess for other reasons and it seems to work I am inclined to stick with it.

Is it system dependent maybe?