How do I copy a file in python?

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


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.


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
    

    ---------------------------------------------------------------------------
    | Function          |Copies Metadata|Copies Permissions|Can Specify Buffer|
    ---------------------------------------------------------------------------
    | shutil.copy       |      No       |        Yes       |        No        |
    ---------------------------------------------------------------------------
    | shutil.copyfile   |      No       |         No       |        No        |
    ---------------------------------------------------------------------------
    | shutil.copy2      |     Yes       |        Yes       |        No        |
    ---------------------------------------------------------------------------
    | shutil.copyfileobj|      No       |         No       |       Yes        |
    ---------------------------------------------------------------------------
    
    链接地址: http://www.djcxy.com/p/1124.html

    上一篇: 在Python中,我如何读取文件行

    下一篇: 如何在python中复制文件?