views:

17028

answers:

7

How do I copy a file in python? I couldn't find anything under os.

+51  A: 

shutil has many methods you can use. One of which is:

copyfile(src, dst)

Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.

Swati
What is the difference between copy and copyfile?
Matt
in copy(src, dst) the dst can be a directory.
Owen
Note that not all metadata will be copied, depending on your platform.
Kevin Horn
is this solution cross platform?
superjoe30
yes, it is......
Swati
A: 

shutil may have what your looking for.

ctcherry
+2  A: 

Look at module shutils. It contains function copyfile(src, dst)

Giacomo Degli Esposti
+2  A: 

Use the shutils module. http://docs.python.org/lib/module-shutil.html

copyfile(src, dst)

Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.

Take a look at http://docs.python.org/lib/filesys.html for all the file and directory handling functions available in standard Python modules.

Airsource Ltd
+15  A: 
import shutil
shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')

or

shutil.copy2('/dir/file.ext', '/new/dir')

copy2 is also often useful, it preserves the original modification and access info (mtime and atime) in the file metadata.

bvmou
You should explain what benefits copy2 has if you want your answer to be more helpful.
ΤΖΩΤΖΙΟΥ
+9  A: 

In case you are stuck with Python 2.3 (as I am) you may notice that there is no shutils. But copying a file is a relatively straightforward operation.

def copyfile(source, dest, buffer_size=1024*1024):
    """
    Copy a file from source to dest. source and dest
    can either be strings or any object with a read or
    write method, like StringIO for example.
    """
    if not hasattr(source, 'read'):
        source = open(source, 'rb')
    if not hasattr(dest, 'write'):
        dest = open(dest, 'wb')

    while 1:
        copy_buffer = source.read(buffer_size)
        if copy_buffer:
            dest.write(copy_buffer)
        else:
            break

    source.close()
    dest.close()
pi
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it _is_ in Python 2.3. Nevertheless I leave this function here as an example.
pi