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

share|improve this question
57  
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module. – waldol1 Oct 16 '13 at 20:58

12 Answers 12

up vote 1489 down vote accepted

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

from shutil import copyfile

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.

share|improve this answer
61  
What is the difference between copy and copyfile? – Matt Sep 23 '08 at 19:47
210  
in copy(src, dst) the dst can be a directory. – Owen Sep 23 '08 at 19:51
16  
Note that not all metadata will be copied, depending on your platform. – Kevin Horn Oct 19 '09 at 20:50
1  
from shutil import copyFile ImportError: cannot import name copyFile – Mona Jalal Dec 3 '17 at 19:50
1  
@MonaJalal It's case sensitive, don't use capital F. – antonagestam Dec 22 '17 at 17:39
---------------------------------------------------------------------------
| Function          |Copies Metadata|Copies Permissions|Can Specify Buffer|
---------------------------------------------------------------------------
| shutil.copy       |      No       |        Yes       |        No        |
---------------------------------------------------------------------------
| shutil.copyfile   |      No       |         No       |        No        |
---------------------------------------------------------------------------
| shutil.copy2      |     Yes       |        Yes       |        No        |
---------------------------------------------------------------------------
| shutil.copyfileobj|      No       |         No       |       Yes        |
---------------------------------------------------------------------------
share|improve this answer
44  
+1 tables such as these go underappreciated when they are such a great tool for understanding families of functions. Another excellent one -- for beginners especially -- is the one for file open modes – Aaron3468 Sep 3 '16 at 19:50
1  
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name. – Conchylicultor Oct 10 '16 at 18:47
    
@Conchylicultor - Good idea. Can you give me some link for it? I cannot find it in official docs. thank you. – jezrael Oct 13 '16 at 10:29
1  
@jezrael Extracted from the doc: dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path. (here: docs.python.org/3/library/shutil.html#shutil.copyfile) – Conchylicultor Feb 1 '17 at 21:48

I suggest using Swati's answer, but supposing you have a text file and don't want to use additional libraries in your code just to copy it, you can use the following one-liner:

with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
share|improve this answer
    
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations. – maxschlepzig Oct 2 '17 at 7:11
    
Is that true? I think .read() and .write() are buffered by default (at least for CPython). – soundstripe Nov 17 '17 at 1:39

You can use one of the copy functions from the shutil package:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata  
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy              ✔             ✔                 ☐           ☐
shutil.copy2             ✔             ✔                 ☐           ✔
shutil.copyfile          ☐             ☐                 ☐           ☐
shutil.copyfileobj       ☐             ☐                 ✔           ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Example:

import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
share|improve this answer

copy2(src,dst) is often more useful than copyfile(src,dst) because:

  • it allows dst to be a directory (instead of the complete target filename), in which case the basename of src is used for creating the new file;
  • it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).

Here is a short example:

import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
share|improve this answer
3  
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks! – sage Jun 23 '11 at 17:33
12  
Your answer is a bit deceptive. Your choice of words for shutil.copy2('/dir/file.ext', '/new/dir') suggests that copy2 will create a new directory. But in this case dir must already exist as a directory or else file.ext will be copied to a new file called dir. – Matthew Alpert Oct 31 '13 at 19:29
11  
I am trying to randomly copy 100k files from 1 million files. copyfile is considerably faster than copy2 – Vijay May 7 '14 at 8:31
1  
am I correct to assume that shutil.copy2('/dir/file.ext', '/new/dir/') (with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name? – Zak Aug 19 '15 at 18:56
    
@Vijay I believe this overhead is due to copying the metadata. – Sheljohn Mar 13 '17 at 17:57
from subprocess import call
call("cp -p <file> <file>", shell=True)
share|improve this answer
8  
This depends on the platform, so i would not use is. – Kevin Meier Sep 13 '16 at 10:02
3  
Such a call is unsecure. Please refere to the subproces docu about it. – buhtz Apr 2 '17 at 7:57
1  
this is not portable, and unnecessary since you can just use shutil. – Corey Goldberg Jun 12 '17 at 14:05
2  
Hmm why Python, then? – Baris Demiray Jul 7 '17 at 9:29

Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the shutil stdlib module for that.

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while 1:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

If you want to copy by filename you could do something like this:

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)
share|improve this answer
24  
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. Mar 31 '09 at 15:20
3  
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform. – LaC Jan 16 '12 at 18:01
2  
True. Looking at the shutil docs, the copyfile function also won't copy metadata. – pi. Jan 17 '12 at 15:08
    
BTW, if you want to copy the contents between two file-like objects, there's shutil.copyfileobj(fsrc, fdst) – Haroldo_OK Aug 19 '14 at 13:14
2  
Yes, I'm not sure why you wouldn't just copy the source of shutil.copyfileobj. Also, you don't have any try, finally to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like how shutil.copyfile wraps shutil.copyfileobj. – ErlVolton Oct 28 '14 at 18:48

For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file.

for line in open("file.txt", "r"):
    list.append(line)
    if len(list) == 1000000: 
        output.writelines(list)
        del list[:]
share|improve this answer
1  
this seems a little redundant since the writer should handle buffering. for l in open('file.txt','r'): output.write(l) should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try with output.write(read(n)); output.flush() where n is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus. – owns Jun 12 '15 at 17:30
1  
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is). – ytpillai Jun 13 '15 at 18:42
    
Very true. Coding for teaching and coding for efficiency are very different. – owns Jun 15 '15 at 17:47
    
@owns To add to this question a year later, writelines() has shown slightly better performance over write() since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed. – ytpillai Nov 30 '16 at 3:33
1  
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.‌​c. Also, the file stream is already open, so write wouldn't need to reopen it every time. – owns May 3 '17 at 0:24

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

share|improve this answer

You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')

or as I did it,

os.system('cp '+ rawfile + ' rawdata.dat')

where rawfile is the name that I had generated inside the program.

This is a Linux only solution

share|improve this answer
5  
this is not portable, and unnecessary since you can just use shutil. – Corey Goldberg Jun 12 '17 at 14:05
2  
Even when shutil is not available - subprocess.run() (without shell=True!) is the better alternative to os.system(). – maxschlepzig Jul 9 '17 at 11:52

Use the shutil module.

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 filesys for all the file and directory handling functions available in standard Python modules.

share|improve this answer
7  
If you had answer 2 minutes earlier, your (current) 7 upvotes would be 382. It makes me think... Seems you've got no use for that, though. – Juh_ Feb 27 '14 at 11:58

Directory and File copy example - From Tim Golden's Python Stuff:

http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html

import os
import shutil
import tempfile

filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2

shutil.copy (filename1, filename2)

if os.path.isfile (filename2): print "Success"

dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2

shutil.copytree (dirname1, dirname2)

if os.path.isdir (dirname2): print "Success"
share|improve this answer

protected by jezrael Mar 16 '16 at 11:40

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.