How do I copy a file in Python?

前端 未结 16 2268
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 07:12

How do I copy a file in Python?

I couldn\'t find anything under os.

16条回答
  •  攒了一身酷
    2020-11-21 07:41

    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
    

提交回复
热议问题