How do I copy a file in Python?How to copy a file along with directory structure/path using python?Python: How to Copy Files FastHow to copy a file to a specific folder in a Python script?Copying and renaming excel files with PythonWriting from .txt to .md in pythonHow do I get Python to read and extract words from a text file?How to get python to copy files to desktopPython + OpenCV - Copying an image to some directoryPython copy file but keep originalHow to copy a file in pythonHow do I check whether a file exists without exceptions?Calling an external command in PythonHow can I safely create a nested directory in Python?How can I make a time delay in Python?How do I include a JavaScript file in another JavaScript file?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?How to copy a folder from remote to local using scp?What is the difference between the `COPY` and `ADD` commands in a Dockerfile?

Why do people keep telling me that I am a bad photographer?

Indentation Tex

As a GM, is it bad form to ask for a moment to think when improvising?

Has the United States ever had a non-Christian President?

When does tabularx decide to break the cell entry instead of reducing the columns separation?

Should I simplify my writing in a foreign country?

Python 3 - simple temperature program

Is Benjen dead?

Is there a word for food that's gone 'bad', but is still edible?

How do I calculate how many of an item I'll have in this inventory system?

Does "Captain Marvel" contain spoilers for "Avengers: Infinity War"?

Would you use "llamarse" for an animal's name?

Agena docking and RCS Brakes in First Man

How long would it take for people to notice a mass disappearance?

Change in "can't be countered" wording

Why is "breaking the mould" positively connoted?

Are the Night's Watch still required?

History of the kernel of a homomorphism?

Why symmetry transformations have to commute with Hamiltonian?

Endgame puzzle: How to avoid stalemate and win?

Start job from another SQL server instance

How to deal with employer who keeps me at work after working hours

Notation: What does the tilde bellow of the Expectation mean?

Is there a word that describes the unjustified use of a more complex word?



How do I copy a file in Python?


How to copy a file along with directory structure/path using python?Python: How to Copy Files FastHow to copy a file to a specific folder in a Python script?Copying and renaming excel files with PythonWriting from .txt to .md in pythonHow do I get Python to read and extract words from a text file?How to get python to copy files to desktopPython + OpenCV - Copying an image to some directoryPython copy file but keep originalHow to copy a file in pythonHow do I check whether a file exists without exceptions?Calling an external command in PythonHow can I safely create a nested directory in Python?How can I make a time delay in Python?How do I include a JavaScript file in another JavaScript file?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?How to copy a folder from remote to local using scp?What is the difference between the `COPY` and `ADD` commands in a Dockerfile?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1848















How do I copy a file in Python?



I couldn't find anything under os.










share|improve this question



















  • 87





    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

















1848















How do I copy a file in Python?



I couldn't find anything under os.










share|improve this question



















  • 87





    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













1848












1848








1848


299






How do I copy a file in Python?



I couldn't find anything under os.










share|improve this question
















How do I copy a file in Python?



I couldn't find anything under os.







python file copy filesystems copyfile






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 15 '18 at 1:59









Peter Mortensen

14k1987114




14k1987114










asked Sep 23 '08 at 19:23









MattMatt

27.2k254856




27.2k254856







  • 87





    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












  • 87





    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







87




87





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





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












15 Answers
15






active

oldest

votes


















2276














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




















  • 101





    What is the difference between copy and copyfile?

    – Matt
    Sep 23 '08 at 19:47






  • 313





    in copy(src, dst) the dst can be a directory.

    – Owen
    Sep 23 '08 at 19:51






  • 28





    Note that not all metadata will be copied, depending on your platform.

    – Kevin Horn
    Oct 19 '09 at 20:50






  • 14





    @MonaJalal It's case sensitive, don't use capital F.

    – antonagestam
    Dec 22 '17 at 17:39






  • 3





    Note that it is not an atomic operation. Take care using it in a threaded application.

    – Waterbyte
    Oct 22 '18 at 11:53


















821














┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘





share|improve this answer




















  • 6





    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






  • 2





    @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






  • 7





    Now this is just bad, bad API design.

    – One Man Monkey Squad
    Jan 16 at 13:51






  • 2





    What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

    – Katie S
    Feb 7 at 22:00











  • According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

    – FabioSpaghetti
    Feb 8 at 14:29


















640














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






  • 20





    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







  • 16





    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






  • 4





    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






  • 1





    @Vijay I believe this overhead is due to copying the metadata.

    – Sheljohn
    Mar 13 '17 at 17:57


















87














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 True:
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



















83














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




















  • 3





    Just curious, how did you generate that table?

    – lightalchemist
    Dec 2 '18 at 7:40






  • 1





    @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

    – maxschlepzig
    Dec 2 '18 at 17:02


















62














In Python, you can copy the files using




  • shutil module


  • os module


  • subprocess module


import os
import shutil
import subprocess



1) Copying files using shutil module



shutil.copyfile signature



shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copyfile('source.txt', 'destination.txt')



shutil.copy signature



shutil.copy(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy('source.txt', 'destination.txt')



shutil.copy2 signature



shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy2('source.txt', 'destination.txt')



shutil.copyfileobj signature



shutil.copyfileobj(src_file_object, dest_file_object[, length])

# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')

file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')

shutil.copyfileobj(f_src, f_dest)



2) Copying files using os module



os.popen signature



os.popen(cmd[, mode[, bufsize]])

# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')

# In Windows
os.popen('copy source.txt destination.txt')



os.system signature



os.system(command)


# In Linux/Unix
os.system('cp source.txt destination.txt')

# In Windows
os.system('copy source.txt destination.txt')



3) Copying files using subprocess module



subprocess.call signature



subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)

# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)



subprocess.check_output signature



subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)

# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)







share|improve this answer


















  • 2





    Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

    – Marcel Waldvogel
    Apr 29 at 3:03






  • 1





    Why do you list so many bad alternatives to the shutil copy functions?

    – maxschlepzig
    Apr 29 at 11:08











  • shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

    – Jean-François Fabre
    Apr 29 at 17:19












  • os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

    – Jean-François Fabre
    Apr 29 at 18:12












  • @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

    – kmario23
    Apr 29 at 20:03


















59














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
































    44














    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






























      13














      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




















      • 9





        this is not portable, and unnecessary since you can just use shutil.

        – Corey Goldberg
        Jun 12 '17 at 14:05






      • 4





        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






      • 1





        shutil is more portable

        – Hiadore
        Mar 12 at 9:07











      • subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

        – Marcel Waldvogel
        Apr 29 at 3:09











      • try that with filenames with spaces in it.

        – Jean-François Fabre
        Apr 29 at 17:21


















      10














      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


















      • 2





        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



















      10














      from subprocess import call
      call("cp -p <file> <file>", shell=True)





      share|improve this answer


















      • 10





        This depends on the platform, so i would not use is.

        – Kevin Meier
        Sep 13 '16 at 10:02






      • 5





        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











      • Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

        – MilkyWay90
        Nov 9 '18 at 15:51


















      10














      Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.



      shutil_methods =
      'copy':['shutil.copyfileobj',
      'shutil.copyfile',
      'shutil.copymode',
      'shutil.copystat',
      'shutil.copy',
      'shutil.copy2',
      'shutil.copytree',],
      'move':['shutil.rmtree',
      'shutil.move',],
      'exception': ['exception shutil.SameFileError',
      'exception shutil.Error'],
      'others':['shutil.disk_usage',
      'shutil.chown',
      'shutil.which',
      'shutil.ignore_patterns',]



      Secondly, explain methods of copy in exmaples:





      1. shutil.copyfileobj(fsrc, fdst[, length]) manipulate opened objects



      In [3]: src = '~/Documents/Head+First+SQL.pdf'
      In [4]: dst = '~/desktop'
      In [5]: shutil.copyfileobj(src, dst)
      AttributeError: 'str' object has no attribute 'read'
      #copy the file object
      In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
      ...: shutil.copyfileobj(f1, f2)
      In [8]: os.stat(os.path.join(dst,'test.pdf'))
      Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)




      1. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy and rename



      In [9]: shutil.copyfile(src, dst)
      IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
      #so dst should be a filename instead of a directory name




      1. shutil.copy() Copy without preseving the metadata



      In [10]: shutil.copy(src, dst)
      Out[10]: ~/desktop/Head+First+SQL.pdf'
      #check their metadata
      In [25]: os.stat(src)
      Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
      In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
      Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
      # st_atime,st_mtime,st_ctime changed




      1. shutil.copy2() Copy with preseving the metadata



      In [30]: shutil.copy2(src, dst)
      Out[30]: ~/desktop/Head+First+SQL.pdf'
      In [31]: os.stat(src)
      Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
      In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
      Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
      # Preseved st_mtime



      1. `shutil.copytree()``



      Recursively copy an entire directory tree rooted at src, returning the destination directory






      share|improve this answer






























        10














        For small files and using only python built-ins, you can use the following one-liner:



        with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())


        As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.






        share|improve this answer




















        • 3





          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






        • 1





          Is that true? I think .read() and .write() are buffered by default (at least for CPython).

          – soundstripe
          Nov 17 '17 at 1:39











        • @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

          – maxschlepzig
          Apr 29 at 11:00











        • @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

          – yellow01
          Apr 29 at 18:36


















        2














        open(destination, 'wb').write(open(source, 'rb').read())


        Open the source file in read mode, and write to destination file in write mode.






        share|improve this answer

























        • The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

          – Raúl Salinas-Monteagudo
          Mar 29 at 11:06











        • All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

          – connectyourcharger
          Mar 30 at 22:19






        • 1





          Isn't that missing the .close() on all of those open(...)s?

          – luckydonald
          Apr 22 at 22:37











        • No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

          – Sundeep Borra
          Apr 23 at 21:19











        • AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

          – Marcel Waldvogel
          Apr 29 at 3:17


















        1














        As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):



        from pathlib import Path

        source = Path('../path/to/my/file.txt')
        destination = Path('../path/where/i/want/to/store/it.txt')
        destination.write_bytes(source.read_bytes())


        write_bytes will overwrite whatever was at the destination's location






        share|improve this answer


















        • 1





          And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

          – Marcel Waldvogel
          Apr 29 at 3:21











        • at least it doesn't repeat the same solutions over and over again.

          – Jean-François Fabre
          Apr 29 at 18:16









        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?














        15 Answers
        15






        active

        oldest

        votes








        15 Answers
        15






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2276














        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




















        • 101





          What is the difference between copy and copyfile?

          – Matt
          Sep 23 '08 at 19:47






        • 313





          in copy(src, dst) the dst can be a directory.

          – Owen
          Sep 23 '08 at 19:51






        • 28





          Note that not all metadata will be copied, depending on your platform.

          – Kevin Horn
          Oct 19 '09 at 20:50






        • 14





          @MonaJalal It's case sensitive, don't use capital F.

          – antonagestam
          Dec 22 '17 at 17:39






        • 3





          Note that it is not an atomic operation. Take care using it in a threaded application.

          – Waterbyte
          Oct 22 '18 at 11:53















        2276














        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




















        • 101





          What is the difference between copy and copyfile?

          – Matt
          Sep 23 '08 at 19:47






        • 313





          in copy(src, dst) the dst can be a directory.

          – Owen
          Sep 23 '08 at 19:51






        • 28





          Note that not all metadata will be copied, depending on your platform.

          – Kevin Horn
          Oct 19 '09 at 20:50






        • 14





          @MonaJalal It's case sensitive, don't use capital F.

          – antonagestam
          Dec 22 '17 at 17:39






        • 3





          Note that it is not an atomic operation. Take care using it in a threaded application.

          – Waterbyte
          Oct 22 '18 at 11:53













        2276












        2276








        2276







        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















        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














        share|improve this answer



        share|improve this answer








        edited Mar 31 at 5:14









        Mr. Me

        3,37012337




        3,37012337










        answered Sep 23 '08 at 19:25









        SwatiSwati

        27.2k43152




        27.2k43152







        • 101





          What is the difference between copy and copyfile?

          – Matt
          Sep 23 '08 at 19:47






        • 313





          in copy(src, dst) the dst can be a directory.

          – Owen
          Sep 23 '08 at 19:51






        • 28





          Note that not all metadata will be copied, depending on your platform.

          – Kevin Horn
          Oct 19 '09 at 20:50






        • 14





          @MonaJalal It's case sensitive, don't use capital F.

          – antonagestam
          Dec 22 '17 at 17:39






        • 3





          Note that it is not an atomic operation. Take care using it in a threaded application.

          – Waterbyte
          Oct 22 '18 at 11:53












        • 101





          What is the difference between copy and copyfile?

          – Matt
          Sep 23 '08 at 19:47






        • 313





          in copy(src, dst) the dst can be a directory.

          – Owen
          Sep 23 '08 at 19:51






        • 28





          Note that not all metadata will be copied, depending on your platform.

          – Kevin Horn
          Oct 19 '09 at 20:50






        • 14





          @MonaJalal It's case sensitive, don't use capital F.

          – antonagestam
          Dec 22 '17 at 17:39






        • 3





          Note that it is not an atomic operation. Take care using it in a threaded application.

          – Waterbyte
          Oct 22 '18 at 11:53







        101




        101





        What is the difference between copy and copyfile?

        – Matt
        Sep 23 '08 at 19:47





        What is the difference between copy and copyfile?

        – Matt
        Sep 23 '08 at 19:47




        313




        313





        in copy(src, dst) the dst can be a directory.

        – Owen
        Sep 23 '08 at 19:51





        in copy(src, dst) the dst can be a directory.

        – Owen
        Sep 23 '08 at 19:51




        28




        28





        Note that not all metadata will be copied, depending on your platform.

        – Kevin Horn
        Oct 19 '09 at 20:50





        Note that not all metadata will be copied, depending on your platform.

        – Kevin Horn
        Oct 19 '09 at 20:50




        14




        14





        @MonaJalal It's case sensitive, don't use capital F.

        – antonagestam
        Dec 22 '17 at 17:39





        @MonaJalal It's case sensitive, don't use capital F.

        – antonagestam
        Dec 22 '17 at 17:39




        3




        3





        Note that it is not an atomic operation. Take care using it in a threaded application.

        – Waterbyte
        Oct 22 '18 at 11:53





        Note that it is not an atomic operation. Take care using it in a threaded application.

        – Waterbyte
        Oct 22 '18 at 11:53













        821














        ┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
        │ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
        ├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
        │shutil.copy │ No │ Yes │ No │ Yes │
        │shutil.copyfile │ No │ No │ No │ No │
        │shutil.copy2 │ Yes │ Yes │ No │ Yes │
        │shutil.copyfileobj│ No │ No │ Yes │ No │
        └──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘





        share|improve this answer




















        • 6





          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






        • 2





          @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






        • 7





          Now this is just bad, bad API design.

          – One Man Monkey Squad
          Jan 16 at 13:51






        • 2





          What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

          – Katie S
          Feb 7 at 22:00











        • According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

          – FabioSpaghetti
          Feb 8 at 14:29















        821














        ┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
        │ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
        ├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
        │shutil.copy │ No │ Yes │ No │ Yes │
        │shutil.copyfile │ No │ No │ No │ No │
        │shutil.copy2 │ Yes │ Yes │ No │ Yes │
        │shutil.copyfileobj│ No │ No │ Yes │ No │
        └──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘





        share|improve this answer




















        • 6





          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






        • 2





          @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






        • 7





          Now this is just bad, bad API design.

          – One Man Monkey Squad
          Jan 16 at 13:51






        • 2





          What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

          – Katie S
          Feb 7 at 22:00











        • According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

          – FabioSpaghetti
          Feb 8 at 14:29













        821












        821








        821







        ┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
        │ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
        ├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
        │shutil.copy │ No │ Yes │ No │ Yes │
        │shutil.copyfile │ No │ No │ No │ No │
        │shutil.copy2 │ Yes │ Yes │ No │ Yes │
        │shutil.copyfileobj│ No │ No │ Yes │ No │
        └──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘





        share|improve this answer















        ┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
        │ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
        ├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
        │shutil.copy │ No │ Yes │ No │ Yes │
        │shutil.copyfile │ No │ No │ No │ No │
        │shutil.copy2 │ Yes │ Yes │ No │ Yes │
        │shutil.copyfileobj│ No │ No │ Yes │ No │
        └──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Oct 24 '18 at 1:59









        jcrs

        1539




        1539










        answered May 20 '15 at 20:01









        jezraeljezrael

        365k26332415




        365k26332415







        • 6





          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






        • 2





          @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






        • 7





          Now this is just bad, bad API design.

          – One Man Monkey Squad
          Jan 16 at 13:51






        • 2





          What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

          – Katie S
          Feb 7 at 22:00











        • According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

          – FabioSpaghetti
          Feb 8 at 14:29












        • 6





          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






        • 2





          @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






        • 7





          Now this is just bad, bad API design.

          – One Man Monkey Squad
          Jan 16 at 13:51






        • 2





          What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

          – Katie S
          Feb 7 at 22:00











        • According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

          – FabioSpaghetti
          Feb 8 at 14:29







        6




        6





        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





        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




        2




        2





        @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





        @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




        7




        7





        Now this is just bad, bad API design.

        – One Man Monkey Squad
        Jan 16 at 13:51





        Now this is just bad, bad API design.

        – One Man Monkey Squad
        Jan 16 at 13:51




        2




        2





        What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

        – Katie S
        Feb 7 at 22:00





        What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?

        – Katie S
        Feb 7 at 22:00













        According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

        – FabioSpaghetti
        Feb 8 at 14:29





        According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!

        – FabioSpaghetti
        Feb 8 at 14:29











        640














        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






        • 20





          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







        • 16





          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






        • 4





          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






        • 1





          @Vijay I believe this overhead is due to copying the metadata.

          – Sheljohn
          Mar 13 '17 at 17:57















        640














        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






        • 20





          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







        • 16





          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






        • 4





          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






        • 1





          @Vijay I believe this overhead is due to copying the metadata.

          – Sheljohn
          Mar 13 '17 at 17:57













        640












        640








        640







        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















        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














        share|improve this answer



        share|improve this answer








        edited Mar 13 '17 at 17:56









        Sheljohn

        4,08622656




        4,08622656










        answered Sep 23 '08 at 19:29









        unmountedunmounted

        23.6k144957




        23.6k144957







        • 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






        • 20





          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







        • 16





          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






        • 4





          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






        • 1





          @Vijay I believe this overhead is due to copying the metadata.

          – Sheljohn
          Mar 13 '17 at 17:57












        • 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






        • 20





          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







        • 16





          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






        • 4





          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






        • 1





          @Vijay I believe this overhead is due to copying the metadata.

          – Sheljohn
          Mar 13 '17 at 17:57







        3




        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





        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




        20




        20





        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






        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





        16




        16





        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





        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




        4




        4





        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





        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




        1




        1





        @Vijay I believe this overhead is due to copying the metadata.

        – Sheljohn
        Mar 13 '17 at 17:57





        @Vijay I believe this overhead is due to copying the metadata.

        – Sheljohn
        Mar 13 '17 at 17:57











        87














        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 True:
        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
















        87














        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 True:
        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














        87












        87








        87







        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 True:
        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















        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 True:
        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














        share|improve this answer



        share|improve this answer








        edited Apr 10 '18 at 15:27









        Eric O Lebigot

        58k36171220




        58k36171220










        answered Sep 24 '08 at 7:21









        pi.pi.

        13.9k53052




        13.9k53052







        • 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













        • 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








        24




        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





        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




        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





        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




        2





        True. Looking at the shutil docs, the copyfile function also won't copy metadata.

        – pi.
        Jan 17 '12 at 15:08





        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





        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




        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






        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












        83














        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




















        • 3





          Just curious, how did you generate that table?

          – lightalchemist
          Dec 2 '18 at 7:40






        • 1





          @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

          – maxschlepzig
          Dec 2 '18 at 17:02















        83














        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




















        • 3





          Just curious, how did you generate that table?

          – lightalchemist
          Dec 2 '18 at 7:40






        • 1





          @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

          – maxschlepzig
          Dec 2 '18 at 17:02













        83












        83








        83







        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















        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














        share|improve this answer



        share|improve this answer








        edited Aug 15 '18 at 17:26

























        answered Jul 9 '17 at 11:50









        maxschlepzigmaxschlepzig

        14.5k775112




        14.5k775112







        • 3





          Just curious, how did you generate that table?

          – lightalchemist
          Dec 2 '18 at 7:40






        • 1





          @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

          – maxschlepzig
          Dec 2 '18 at 17:02












        • 3





          Just curious, how did you generate that table?

          – lightalchemist
          Dec 2 '18 at 7:40






        • 1





          @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

          – maxschlepzig
          Dec 2 '18 at 17:02







        3




        3





        Just curious, how did you generate that table?

        – lightalchemist
        Dec 2 '18 at 7:40





        Just curious, how did you generate that table?

        – lightalchemist
        Dec 2 '18 at 7:40




        1




        1





        @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

        – maxschlepzig
        Dec 2 '18 at 17:02





        @lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.

        – maxschlepzig
        Dec 2 '18 at 17:02











        62














        In Python, you can copy the files using




        • shutil module


        • os module


        • subprocess module


        import os
        import shutil
        import subprocess



        1) Copying files using shutil module



        shutil.copyfile signature



        shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copyfile('source.txt', 'destination.txt')



        shutil.copy signature



        shutil.copy(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy('source.txt', 'destination.txt')



        shutil.copy2 signature



        shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy2('source.txt', 'destination.txt')



        shutil.copyfileobj signature



        shutil.copyfileobj(src_file_object, dest_file_object[, length])

        # example
        file_src = 'source.txt'
        f_src = open(file_src, 'rb')

        file_dest = 'destination.txt'
        f_dest = open(file_dest, 'wb')

        shutil.copyfileobj(f_src, f_dest)



        2) Copying files using os module



        os.popen signature



        os.popen(cmd[, mode[, bufsize]])

        # example
        # In Unix/Linux
        os.popen('cp source.txt destination.txt')

        # In Windows
        os.popen('copy source.txt destination.txt')



        os.system signature



        os.system(command)


        # In Linux/Unix
        os.system('cp source.txt destination.txt')

        # In Windows
        os.system('copy source.txt destination.txt')



        3) Copying files using subprocess module



        subprocess.call signature



        subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.call('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.call('copy source.txt destination.txt', shell=True)



        subprocess.check_output signature



        subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.check_output('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.check_output('copy source.txt destination.txt', shell=True)







        share|improve this answer


















        • 2





          Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

          – Marcel Waldvogel
          Apr 29 at 3:03






        • 1





          Why do you list so many bad alternatives to the shutil copy functions?

          – maxschlepzig
          Apr 29 at 11:08











        • shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

          – Jean-François Fabre
          Apr 29 at 17:19












        • os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

          – Jean-François Fabre
          Apr 29 at 18:12












        • @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

          – kmario23
          Apr 29 at 20:03















        62














        In Python, you can copy the files using




        • shutil module


        • os module


        • subprocess module


        import os
        import shutil
        import subprocess



        1) Copying files using shutil module



        shutil.copyfile signature



        shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copyfile('source.txt', 'destination.txt')



        shutil.copy signature



        shutil.copy(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy('source.txt', 'destination.txt')



        shutil.copy2 signature



        shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy2('source.txt', 'destination.txt')



        shutil.copyfileobj signature



        shutil.copyfileobj(src_file_object, dest_file_object[, length])

        # example
        file_src = 'source.txt'
        f_src = open(file_src, 'rb')

        file_dest = 'destination.txt'
        f_dest = open(file_dest, 'wb')

        shutil.copyfileobj(f_src, f_dest)



        2) Copying files using os module



        os.popen signature



        os.popen(cmd[, mode[, bufsize]])

        # example
        # In Unix/Linux
        os.popen('cp source.txt destination.txt')

        # In Windows
        os.popen('copy source.txt destination.txt')



        os.system signature



        os.system(command)


        # In Linux/Unix
        os.system('cp source.txt destination.txt')

        # In Windows
        os.system('copy source.txt destination.txt')



        3) Copying files using subprocess module



        subprocess.call signature



        subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.call('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.call('copy source.txt destination.txt', shell=True)



        subprocess.check_output signature



        subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.check_output('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.check_output('copy source.txt destination.txt', shell=True)







        share|improve this answer


















        • 2





          Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

          – Marcel Waldvogel
          Apr 29 at 3:03






        • 1





          Why do you list so many bad alternatives to the shutil copy functions?

          – maxschlepzig
          Apr 29 at 11:08











        • shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

          – Jean-François Fabre
          Apr 29 at 17:19












        • os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

          – Jean-François Fabre
          Apr 29 at 18:12












        • @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

          – kmario23
          Apr 29 at 20:03













        62












        62








        62







        In Python, you can copy the files using




        • shutil module


        • os module


        • subprocess module


        import os
        import shutil
        import subprocess



        1) Copying files using shutil module



        shutil.copyfile signature



        shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copyfile('source.txt', 'destination.txt')



        shutil.copy signature



        shutil.copy(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy('source.txt', 'destination.txt')



        shutil.copy2 signature



        shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy2('source.txt', 'destination.txt')



        shutil.copyfileobj signature



        shutil.copyfileobj(src_file_object, dest_file_object[, length])

        # example
        file_src = 'source.txt'
        f_src = open(file_src, 'rb')

        file_dest = 'destination.txt'
        f_dest = open(file_dest, 'wb')

        shutil.copyfileobj(f_src, f_dest)



        2) Copying files using os module



        os.popen signature



        os.popen(cmd[, mode[, bufsize]])

        # example
        # In Unix/Linux
        os.popen('cp source.txt destination.txt')

        # In Windows
        os.popen('copy source.txt destination.txt')



        os.system signature



        os.system(command)


        # In Linux/Unix
        os.system('cp source.txt destination.txt')

        # In Windows
        os.system('copy source.txt destination.txt')



        3) Copying files using subprocess module



        subprocess.call signature



        subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.call('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.call('copy source.txt destination.txt', shell=True)



        subprocess.check_output signature



        subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.check_output('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.check_output('copy source.txt destination.txt', shell=True)







        share|improve this answer













        In Python, you can copy the files using




        • shutil module


        • os module


        • subprocess module


        import os
        import shutil
        import subprocess



        1) Copying files using shutil module



        shutil.copyfile signature



        shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copyfile('source.txt', 'destination.txt')



        shutil.copy signature



        shutil.copy(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy('source.txt', 'destination.txt')



        shutil.copy2 signature



        shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

        # example
        shutil.copy2('source.txt', 'destination.txt')



        shutil.copyfileobj signature



        shutil.copyfileobj(src_file_object, dest_file_object[, length])

        # example
        file_src = 'source.txt'
        f_src = open(file_src, 'rb')

        file_dest = 'destination.txt'
        f_dest = open(file_dest, 'wb')

        shutil.copyfileobj(f_src, f_dest)



        2) Copying files using os module



        os.popen signature



        os.popen(cmd[, mode[, bufsize]])

        # example
        # In Unix/Linux
        os.popen('cp source.txt destination.txt')

        # In Windows
        os.popen('copy source.txt destination.txt')



        os.system signature



        os.system(command)


        # In Linux/Unix
        os.system('cp source.txt destination.txt')

        # In Windows
        os.system('copy source.txt destination.txt')



        3) Copying files using subprocess module



        subprocess.call signature



        subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.call('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.call('copy source.txt destination.txt', shell=True)



        subprocess.check_output signature



        subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

        # example (WARNING: setting `shell=True` might be a security-risk)
        # In Linux/Unix
        status = subprocess.check_output('cp source.txt destination.txt', shell=True)

        # In Windows
        status = subprocess.check_output('copy source.txt destination.txt', shell=True)








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 22 '18 at 3:05









        kmario23kmario23

        20.3k56680




        20.3k56680







        • 2





          Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

          – Marcel Waldvogel
          Apr 29 at 3:03






        • 1





          Why do you list so many bad alternatives to the shutil copy functions?

          – maxschlepzig
          Apr 29 at 11:08











        • shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

          – Jean-François Fabre
          Apr 29 at 17:19












        • os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

          – Jean-François Fabre
          Apr 29 at 18:12












        • @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

          – kmario23
          Apr 29 at 20:03












        • 2





          Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

          – Marcel Waldvogel
          Apr 29 at 3:03






        • 1





          Why do you list so many bad alternatives to the shutil copy functions?

          – maxschlepzig
          Apr 29 at 11:08











        • shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

          – Jean-François Fabre
          Apr 29 at 17:19












        • os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

          – Jean-François Fabre
          Apr 29 at 18:12












        • @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

          – kmario23
          Apr 29 at 20:03







        2




        2





        Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

        – Marcel Waldvogel
        Apr 29 at 3:03





        Using single-string commands is bad coding style (flexibility, reliability and security), instead use ['copy', sourcefile, destfile] syntax wherever possible, especially if the parameters are from user input.

        – Marcel Waldvogel
        Apr 29 at 3:03




        1




        1





        Why do you list so many bad alternatives to the shutil copy functions?

        – maxschlepzig
        Apr 29 at 11:08





        Why do you list so many bad alternatives to the shutil copy functions?

        – maxschlepzig
        Apr 29 at 11:08













        shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

        – Jean-François Fabre
        Apr 29 at 17:19






        shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.

        – Jean-François Fabre
        Apr 29 at 17:19














        os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

        – Jean-François Fabre
        Apr 29 at 18:12






        os.popen is deprecated for a while now. and check_output doesn't return the status but the output (which is empty in the case of copy/cp)

        – Jean-François Fabre
        Apr 29 at 18:12














        @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

        – kmario23
        Apr 29 at 20:03





        @Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).

        – kmario23
        Apr 29 at 20:03











        59














        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





























          59














          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



























            59












            59








            59







            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















            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














            share|improve this answer



            share|improve this answer








            edited Sep 7 '14 at 13:06









            flying sheep

            4,62543655




            4,62543655










            answered Sep 23 '08 at 19:27









            Airsource LtdAirsource Ltd

            24.2k136474




            24.2k136474





















                44














                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



























                  44














                  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

























                    44












                    44








                    44







                    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













                    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












                    share|improve this answer



                    share|improve this answer










                    answered Mar 15 '11 at 10:11









                    Noam ManosNoam Manos

                    6,29413541




                    6,29413541





















                        13














                        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




















                        • 9





                          this is not portable, and unnecessary since you can just use shutil.

                          – Corey Goldberg
                          Jun 12 '17 at 14:05






                        • 4





                          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






                        • 1





                          shutil is more portable

                          – Hiadore
                          Mar 12 at 9:07











                        • subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

                          – Marcel Waldvogel
                          Apr 29 at 3:09











                        • try that with filenames with spaces in it.

                          – Jean-François Fabre
                          Apr 29 at 17:21















                        13














                        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




















                        • 9





                          this is not portable, and unnecessary since you can just use shutil.

                          – Corey Goldberg
                          Jun 12 '17 at 14:05






                        • 4





                          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






                        • 1





                          shutil is more portable

                          – Hiadore
                          Mar 12 at 9:07











                        • subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

                          – Marcel Waldvogel
                          Apr 29 at 3:09











                        • try that with filenames with spaces in it.

                          – Jean-François Fabre
                          Apr 29 at 17:21













                        13












                        13








                        13







                        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















                        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














                        share|improve this answer



                        share|improve this answer








                        edited Dec 19 '14 at 23:23









                        James Donnelly

                        102k22159174




                        102k22159174










                        answered Dec 19 '14 at 23:18









                        markmark

                        23522




                        23522







                        • 9





                          this is not portable, and unnecessary since you can just use shutil.

                          – Corey Goldberg
                          Jun 12 '17 at 14:05






                        • 4





                          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






                        • 1





                          shutil is more portable

                          – Hiadore
                          Mar 12 at 9:07











                        • subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

                          – Marcel Waldvogel
                          Apr 29 at 3:09











                        • try that with filenames with spaces in it.

                          – Jean-François Fabre
                          Apr 29 at 17:21












                        • 9





                          this is not portable, and unnecessary since you can just use shutil.

                          – Corey Goldberg
                          Jun 12 '17 at 14:05






                        • 4





                          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






                        • 1





                          shutil is more portable

                          – Hiadore
                          Mar 12 at 9:07











                        • subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

                          – Marcel Waldvogel
                          Apr 29 at 3:09











                        • try that with filenames with spaces in it.

                          – Jean-François Fabre
                          Apr 29 at 17:21







                        9




                        9





                        this is not portable, and unnecessary since you can just use shutil.

                        – Corey Goldberg
                        Jun 12 '17 at 14:05





                        this is not portable, and unnecessary since you can just use shutil.

                        – Corey Goldberg
                        Jun 12 '17 at 14:05




                        4




                        4





                        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





                        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




                        1




                        1





                        shutil is more portable

                        – Hiadore
                        Mar 12 at 9:07





                        shutil is more portable

                        – Hiadore
                        Mar 12 at 9:07













                        subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

                        – Marcel Waldvogel
                        Apr 29 at 3:09





                        subprocess.run() as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat'] form of passing the command line. (However, for copying, shutil and friends are recommended over calling an external program.)

                        – Marcel Waldvogel
                        Apr 29 at 3:09













                        try that with filenames with spaces in it.

                        – Jean-François Fabre
                        Apr 29 at 17:21





                        try that with filenames with spaces in it.

                        – Jean-François Fabre
                        Apr 29 at 17:21











                        10














                        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


















                        • 2





                          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
















                        10














                        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


















                        • 2





                          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














                        10












                        10








                        10







                        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













                        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












                        share|improve this answer



                        share|improve this answer










                        answered May 25 '15 at 5:11









                        ytpillaiytpillai

                        2,3481835




                        2,3481835







                        • 2





                          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













                        • 2





                          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








                        2




                        2





                        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






                        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




                        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






                        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





                        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





                        @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




                        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






                        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












                        10














                        from subprocess import call
                        call("cp -p <file> <file>", shell=True)





                        share|improve this answer


















                        • 10





                          This depends on the platform, so i would not use is.

                          – Kevin Meier
                          Sep 13 '16 at 10:02






                        • 5





                          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











                        • Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

                          – MilkyWay90
                          Nov 9 '18 at 15:51















                        10














                        from subprocess import call
                        call("cp -p <file> <file>", shell=True)





                        share|improve this answer


















                        • 10





                          This depends on the platform, so i would not use is.

                          – Kevin Meier
                          Sep 13 '16 at 10:02






                        • 5





                          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











                        • Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

                          – MilkyWay90
                          Nov 9 '18 at 15:51













                        10












                        10








                        10







                        from subprocess import call
                        call("cp -p <file> <file>", shell=True)





                        share|improve this answer













                        from subprocess import call
                        call("cp -p <file> <file>", shell=True)






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Apr 4 '16 at 7:08









                        deepdivedeepdive

                        2,26621627




                        2,26621627







                        • 10





                          This depends on the platform, so i would not use is.

                          – Kevin Meier
                          Sep 13 '16 at 10:02






                        • 5





                          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











                        • Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

                          – MilkyWay90
                          Nov 9 '18 at 15:51












                        • 10





                          This depends on the platform, so i would not use is.

                          – Kevin Meier
                          Sep 13 '16 at 10:02






                        • 5





                          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











                        • Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

                          – MilkyWay90
                          Nov 9 '18 at 15:51







                        10




                        10





                        This depends on the platform, so i would not use is.

                        – Kevin Meier
                        Sep 13 '16 at 10:02





                        This depends on the platform, so i would not use is.

                        – Kevin Meier
                        Sep 13 '16 at 10:02




                        5




                        5





                        Such a call is unsecure. Please refere to the subproces docu about it.

                        – buhtz
                        Apr 2 '17 at 7:57





                        Such a call is unsecure. Please refere to the subproces docu about it.

                        – buhtz
                        Apr 2 '17 at 7:57




                        1




                        1





                        this is not portable, and unnecessary since you can just use shutil.

                        – Corey Goldberg
                        Jun 12 '17 at 14:05





                        this is not portable, and unnecessary since you can just use shutil.

                        – Corey Goldberg
                        Jun 12 '17 at 14:05




                        2




                        2





                        Hmm why Python, then?

                        – Baris Demiray
                        Jul 7 '17 at 9:29





                        Hmm why Python, then?

                        – Baris Demiray
                        Jul 7 '17 at 9:29













                        Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

                        – MilkyWay90
                        Nov 9 '18 at 15:51





                        Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)

                        – MilkyWay90
                        Nov 9 '18 at 15:51











                        10














                        Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.



                        shutil_methods =
                        'copy':['shutil.copyfileobj',
                        'shutil.copyfile',
                        'shutil.copymode',
                        'shutil.copystat',
                        'shutil.copy',
                        'shutil.copy2',
                        'shutil.copytree',],
                        'move':['shutil.rmtree',
                        'shutil.move',],
                        'exception': ['exception shutil.SameFileError',
                        'exception shutil.Error'],
                        'others':['shutil.disk_usage',
                        'shutil.chown',
                        'shutil.which',
                        'shutil.ignore_patterns',]



                        Secondly, explain methods of copy in exmaples:





                        1. shutil.copyfileobj(fsrc, fdst[, length]) manipulate opened objects



                        In [3]: src = '~/Documents/Head+First+SQL.pdf'
                        In [4]: dst = '~/desktop'
                        In [5]: shutil.copyfileobj(src, dst)
                        AttributeError: 'str' object has no attribute 'read'
                        #copy the file object
                        In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
                        ...: shutil.copyfileobj(f1, f2)
                        In [8]: os.stat(os.path.join(dst,'test.pdf'))
                        Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)




                        1. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy and rename



                        In [9]: shutil.copyfile(src, dst)
                        IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
                        #so dst should be a filename instead of a directory name




                        1. shutil.copy() Copy without preseving the metadata



                        In [10]: shutil.copy(src, dst)
                        Out[10]: ~/desktop/Head+First+SQL.pdf'
                        #check their metadata
                        In [25]: os.stat(src)
                        Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
                        In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                        Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
                        # st_atime,st_mtime,st_ctime changed




                        1. shutil.copy2() Copy with preseving the metadata



                        In [30]: shutil.copy2(src, dst)
                        Out[30]: ~/desktop/Head+First+SQL.pdf'
                        In [31]: os.stat(src)
                        Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
                        In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                        Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
                        # Preseved st_mtime



                        1. `shutil.copytree()``



                        Recursively copy an entire directory tree rooted at src, returning the destination directory






                        share|improve this answer



























                          10














                          Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.



                          shutil_methods =
                          'copy':['shutil.copyfileobj',
                          'shutil.copyfile',
                          'shutil.copymode',
                          'shutil.copystat',
                          'shutil.copy',
                          'shutil.copy2',
                          'shutil.copytree',],
                          'move':['shutil.rmtree',
                          'shutil.move',],
                          'exception': ['exception shutil.SameFileError',
                          'exception shutil.Error'],
                          'others':['shutil.disk_usage',
                          'shutil.chown',
                          'shutil.which',
                          'shutil.ignore_patterns',]



                          Secondly, explain methods of copy in exmaples:





                          1. shutil.copyfileobj(fsrc, fdst[, length]) manipulate opened objects



                          In [3]: src = '~/Documents/Head+First+SQL.pdf'
                          In [4]: dst = '~/desktop'
                          In [5]: shutil.copyfileobj(src, dst)
                          AttributeError: 'str' object has no attribute 'read'
                          #copy the file object
                          In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
                          ...: shutil.copyfileobj(f1, f2)
                          In [8]: os.stat(os.path.join(dst,'test.pdf'))
                          Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)




                          1. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy and rename



                          In [9]: shutil.copyfile(src, dst)
                          IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
                          #so dst should be a filename instead of a directory name




                          1. shutil.copy() Copy without preseving the metadata



                          In [10]: shutil.copy(src, dst)
                          Out[10]: ~/desktop/Head+First+SQL.pdf'
                          #check their metadata
                          In [25]: os.stat(src)
                          Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
                          In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                          Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
                          # st_atime,st_mtime,st_ctime changed




                          1. shutil.copy2() Copy with preseving the metadata



                          In [30]: shutil.copy2(src, dst)
                          Out[30]: ~/desktop/Head+First+SQL.pdf'
                          In [31]: os.stat(src)
                          Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
                          In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                          Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
                          # Preseved st_mtime



                          1. `shutil.copytree()``



                          Recursively copy an entire directory tree rooted at src, returning the destination directory






                          share|improve this answer

























                            10












                            10








                            10







                            Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.



                            shutil_methods =
                            'copy':['shutil.copyfileobj',
                            'shutil.copyfile',
                            'shutil.copymode',
                            'shutil.copystat',
                            'shutil.copy',
                            'shutil.copy2',
                            'shutil.copytree',],
                            'move':['shutil.rmtree',
                            'shutil.move',],
                            'exception': ['exception shutil.SameFileError',
                            'exception shutil.Error'],
                            'others':['shutil.disk_usage',
                            'shutil.chown',
                            'shutil.which',
                            'shutil.ignore_patterns',]



                            Secondly, explain methods of copy in exmaples:





                            1. shutil.copyfileobj(fsrc, fdst[, length]) manipulate opened objects



                            In [3]: src = '~/Documents/Head+First+SQL.pdf'
                            In [4]: dst = '~/desktop'
                            In [5]: shutil.copyfileobj(src, dst)
                            AttributeError: 'str' object has no attribute 'read'
                            #copy the file object
                            In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
                            ...: shutil.copyfileobj(f1, f2)
                            In [8]: os.stat(os.path.join(dst,'test.pdf'))
                            Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)




                            1. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy and rename



                            In [9]: shutil.copyfile(src, dst)
                            IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
                            #so dst should be a filename instead of a directory name




                            1. shutil.copy() Copy without preseving the metadata



                            In [10]: shutil.copy(src, dst)
                            Out[10]: ~/desktop/Head+First+SQL.pdf'
                            #check their metadata
                            In [25]: os.stat(src)
                            Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
                            In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                            Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
                            # st_atime,st_mtime,st_ctime changed




                            1. shutil.copy2() Copy with preseving the metadata



                            In [30]: shutil.copy2(src, dst)
                            Out[30]: ~/desktop/Head+First+SQL.pdf'
                            In [31]: os.stat(src)
                            Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
                            In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                            Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
                            # Preseved st_mtime



                            1. `shutil.copytree()``



                            Recursively copy an entire directory tree rooted at src, returning the destination directory






                            share|improve this answer













                            Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.



                            shutil_methods =
                            'copy':['shutil.copyfileobj',
                            'shutil.copyfile',
                            'shutil.copymode',
                            'shutil.copystat',
                            'shutil.copy',
                            'shutil.copy2',
                            'shutil.copytree',],
                            'move':['shutil.rmtree',
                            'shutil.move',],
                            'exception': ['exception shutil.SameFileError',
                            'exception shutil.Error'],
                            'others':['shutil.disk_usage',
                            'shutil.chown',
                            'shutil.which',
                            'shutil.ignore_patterns',]



                            Secondly, explain methods of copy in exmaples:





                            1. shutil.copyfileobj(fsrc, fdst[, length]) manipulate opened objects



                            In [3]: src = '~/Documents/Head+First+SQL.pdf'
                            In [4]: dst = '~/desktop'
                            In [5]: shutil.copyfileobj(src, dst)
                            AttributeError: 'str' object has no attribute 'read'
                            #copy the file object
                            In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
                            ...: shutil.copyfileobj(f1, f2)
                            In [8]: os.stat(os.path.join(dst,'test.pdf'))
                            Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)




                            1. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy and rename



                            In [9]: shutil.copyfile(src, dst)
                            IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
                            #so dst should be a filename instead of a directory name




                            1. shutil.copy() Copy without preseving the metadata



                            In [10]: shutil.copy(src, dst)
                            Out[10]: ~/desktop/Head+First+SQL.pdf'
                            #check their metadata
                            In [25]: os.stat(src)
                            Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
                            In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                            Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
                            # st_atime,st_mtime,st_ctime changed




                            1. shutil.copy2() Copy with preseving the metadata



                            In [30]: shutil.copy2(src, dst)
                            Out[30]: ~/desktop/Head+First+SQL.pdf'
                            In [31]: os.stat(src)
                            Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
                            In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
                            Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
                            # Preseved st_mtime



                            1. `shutil.copytree()``



                            Recursively copy an entire directory tree rooted at src, returning the destination directory







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 16 '18 at 3:25









                            JawSawJawSaw

                            5,08311941




                            5,08311941





















                                10














                                For small files and using only python built-ins, you can use the following one-liner:



                                with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())


                                As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.






                                share|improve this answer




















                                • 3





                                  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






                                • 1





                                  Is that true? I think .read() and .write() are buffered by default (at least for CPython).

                                  – soundstripe
                                  Nov 17 '17 at 1:39











                                • @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

                                  – maxschlepzig
                                  Apr 29 at 11:00











                                • @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

                                  – yellow01
                                  Apr 29 at 18:36















                                10














                                For small files and using only python built-ins, you can use the following one-liner:



                                with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())


                                As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.






                                share|improve this answer




















                                • 3





                                  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






                                • 1





                                  Is that true? I think .read() and .write() are buffered by default (at least for CPython).

                                  – soundstripe
                                  Nov 17 '17 at 1:39











                                • @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

                                  – maxschlepzig
                                  Apr 29 at 11:00











                                • @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

                                  – yellow01
                                  Apr 29 at 18:36













                                10












                                10








                                10







                                For small files and using only python built-ins, you can use the following one-liner:



                                with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())


                                As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.






                                share|improve this answer















                                For small files and using only python built-ins, you can use the following one-liner:



                                with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())


                                As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Apr 29 at 18:36

























                                answered Aug 15 '17 at 13:46









                                yellow01yellow01

                                889823




                                889823







                                • 3





                                  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






                                • 1





                                  Is that true? I think .read() and .write() are buffered by default (at least for CPython).

                                  – soundstripe
                                  Nov 17 '17 at 1:39











                                • @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

                                  – maxschlepzig
                                  Apr 29 at 11:00











                                • @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

                                  – yellow01
                                  Apr 29 at 18:36












                                • 3





                                  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






                                • 1





                                  Is that true? I think .read() and .write() are buffered by default (at least for CPython).

                                  – soundstripe
                                  Nov 17 '17 at 1:39











                                • @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

                                  – maxschlepzig
                                  Apr 29 at 11:00











                                • @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

                                  – yellow01
                                  Apr 29 at 18:36







                                3




                                3





                                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





                                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




                                1




                                1





                                Is that true? I think .read() and .write() are buffered by default (at least for CPython).

                                – soundstripe
                                Nov 17 '17 at 1:39





                                Is that true? I think .read() and .write() are buffered by default (at least for CPython).

                                – soundstripe
                                Nov 17 '17 at 1:39













                                @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

                                – maxschlepzig
                                Apr 29 at 11:00





                                @soundstripe, Of course this is true. The fact that the file object returned by open() does buffered IO, by default doesn't help you here, because read() is specified as: 'If n is negative or omitted, read until EOF.' That means that the read() returns the complete file content as a string.

                                – maxschlepzig
                                Apr 29 at 11:00













                                @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

                                – yellow01
                                Apr 29 at 18:36





                                @maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.

                                – yellow01
                                Apr 29 at 18:36











                                2














                                open(destination, 'wb').write(open(source, 'rb').read())


                                Open the source file in read mode, and write to destination file in write mode.






                                share|improve this answer

























                                • The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

                                  – Raúl Salinas-Monteagudo
                                  Mar 29 at 11:06











                                • All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

                                  – connectyourcharger
                                  Mar 30 at 22:19






                                • 1





                                  Isn't that missing the .close() on all of those open(...)s?

                                  – luckydonald
                                  Apr 22 at 22:37











                                • No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

                                  – Sundeep Borra
                                  Apr 23 at 21:19











                                • AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

                                  – Marcel Waldvogel
                                  Apr 29 at 3:17















                                2














                                open(destination, 'wb').write(open(source, 'rb').read())


                                Open the source file in read mode, and write to destination file in write mode.






                                share|improve this answer

























                                • The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

                                  – Raúl Salinas-Monteagudo
                                  Mar 29 at 11:06











                                • All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

                                  – connectyourcharger
                                  Mar 30 at 22:19






                                • 1





                                  Isn't that missing the .close() on all of those open(...)s?

                                  – luckydonald
                                  Apr 22 at 22:37











                                • No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

                                  – Sundeep Borra
                                  Apr 23 at 21:19











                                • AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

                                  – Marcel Waldvogel
                                  Apr 29 at 3:17













                                2












                                2








                                2







                                open(destination, 'wb').write(open(source, 'rb').read())


                                Open the source file in read mode, and write to destination file in write mode.






                                share|improve this answer















                                open(destination, 'wb').write(open(source, 'rb').read())


                                Open the source file in read mode, and write to destination file in write mode.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Apr 29 at 18:15









                                Jean-François Fabre

                                107k1060118




                                107k1060118










                                answered Mar 23 at 0:46









                                Sundeep BorraSundeep Borra

                                9951021




                                9951021












                                • The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

                                  – Raúl Salinas-Monteagudo
                                  Mar 29 at 11:06











                                • All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

                                  – connectyourcharger
                                  Mar 30 at 22:19






                                • 1





                                  Isn't that missing the .close() on all of those open(...)s?

                                  – luckydonald
                                  Apr 22 at 22:37











                                • No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

                                  – Sundeep Borra
                                  Apr 23 at 21:19











                                • AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

                                  – Marcel Waldvogel
                                  Apr 29 at 3:17

















                                • The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

                                  – Raúl Salinas-Monteagudo
                                  Mar 29 at 11:06











                                • All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

                                  – connectyourcharger
                                  Mar 30 at 22:19






                                • 1





                                  Isn't that missing the .close() on all of those open(...)s?

                                  – luckydonald
                                  Apr 22 at 22:37











                                • No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

                                  – Sundeep Borra
                                  Apr 23 at 21:19











                                • AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

                                  – Marcel Waldvogel
                                  Apr 29 at 3:17
















                                The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

                                – Raúl Salinas-Monteagudo
                                Mar 29 at 11:06





                                The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.

                                – Raúl Salinas-Monteagudo
                                Mar 29 at 11:06













                                All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

                                – connectyourcharger
                                Mar 30 at 22:19





                                All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.

                                – connectyourcharger
                                Mar 30 at 22:19




                                1




                                1





                                Isn't that missing the .close() on all of those open(...)s?

                                – luckydonald
                                Apr 22 at 22:37





                                Isn't that missing the .close() on all of those open(...)s?

                                – luckydonald
                                Apr 22 at 22:37













                                No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

                                – Sundeep Borra
                                Apr 23 at 21:19





                                No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).

                                – Sundeep Borra
                                Apr 23 at 21:19













                                AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

                                – Marcel Waldvogel
                                Apr 29 at 3:17





                                AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using with (as in the example above) is recommended and not more complicated. Using read() on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader

                                – Marcel Waldvogel
                                Apr 29 at 3:17











                                1














                                As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):



                                from pathlib import Path

                                source = Path('../path/to/my/file.txt')
                                destination = Path('../path/where/i/want/to/store/it.txt')
                                destination.write_bytes(source.read_bytes())


                                write_bytes will overwrite whatever was at the destination's location






                                share|improve this answer


















                                • 1





                                  And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

                                  – Marcel Waldvogel
                                  Apr 29 at 3:21











                                • at least it doesn't repeat the same solutions over and over again.

                                  – Jean-François Fabre
                                  Apr 29 at 18:16















                                1














                                As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):



                                from pathlib import Path

                                source = Path('../path/to/my/file.txt')
                                destination = Path('../path/where/i/want/to/store/it.txt')
                                destination.write_bytes(source.read_bytes())


                                write_bytes will overwrite whatever was at the destination's location






                                share|improve this answer


















                                • 1





                                  And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

                                  – Marcel Waldvogel
                                  Apr 29 at 3:21











                                • at least it doesn't repeat the same solutions over and over again.

                                  – Jean-François Fabre
                                  Apr 29 at 18:16













                                1












                                1








                                1







                                As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):



                                from pathlib import Path

                                source = Path('../path/to/my/file.txt')
                                destination = Path('../path/where/i/want/to/store/it.txt')
                                destination.write_bytes(source.read_bytes())


                                write_bytes will overwrite whatever was at the destination's location






                                share|improve this answer













                                As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):



                                from pathlib import Path

                                source = Path('../path/to/my/file.txt')
                                destination = Path('../path/where/i/want/to/store/it.txt')
                                destination.write_bytes(source.read_bytes())


                                write_bytes will overwrite whatever was at the destination's location







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Apr 25 at 14:09









                                MarcMarc

                                1,5781421




                                1,5781421







                                • 1





                                  And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

                                  – Marcel Waldvogel
                                  Apr 29 at 3:21











                                • at least it doesn't repeat the same solutions over and over again.

                                  – Jean-François Fabre
                                  Apr 29 at 18:16












                                • 1





                                  And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

                                  – Marcel Waldvogel
                                  Apr 29 at 3:21











                                • at least it doesn't repeat the same solutions over and over again.

                                  – Jean-François Fabre
                                  Apr 29 at 18:16







                                1




                                1





                                And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

                                – Marcel Waldvogel
                                Apr 29 at 3:21





                                And then someone uses the code (accidentally or purposefully) on a large file… Using functions from shutil handles all the special cases for you and gives you peace of mind.

                                – Marcel Waldvogel
                                Apr 29 at 3:21













                                at least it doesn't repeat the same solutions over and over again.

                                – Jean-François Fabre
                                Apr 29 at 18:16





                                at least it doesn't repeat the same solutions over and over again.

                                – Jean-François Fabre
                                Apr 29 at 18:16





                                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?



                                Popular posts from this blog

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현