How do I copy a file in Python?

前端 未结 16 2217
隐瞒了意图╮
隐瞒了意图╮ 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:26

    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)
    

提交回复
热议问题