如何在Python中复制文件?

时间:2020-03-06 14:37:17  来源:igfitidea点击:

如何在Python中复制文件?

我在os下找不到任何东西。

解决方案

shutil有许多可以使用的方法。其中之一是:

from shutil import copyfile

copyfile(src, dst)

将名为src的文件的内容复制到名为dst的文件。目标位置必须是可写的;否则,将引发" IOError"异常。如果dst已经存在,它将被替换。特殊文件(例如字符或者块设备和管道)无法使用此功能进行复制。 src和dst是以字符串形式给出的路径名。

查看模块关闭。
它包含函数copyfile(src,dst)

使用shutil模块。

copyfile(src, dst)

将名为src的文件的内容复制到名为dst的文件。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,它将被替换。特殊文件(例如字符或者块设备和管道)无法使用此功能进行复制。 src和dst是以字符串形式给出的路径名。

查看filesys,了解标准Python模块中可用的所有文件和目录处理功能。

通常," copy2(src,dst)"比" copyfile(src,dst)"更有用,因为:

  • 它允许dst成为目录(而不是完整的目标文件名),在这种情况下,src的基名用于创建新文件;
  • 它将原始修改和访问信息(mtime和atime)保留在文件元数据中(但是,这会带来一些开销)。

这是一个简短的示例:

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

拷贝文件是一个相对简单的操作,如下面的示例所示,但是我们应该为此使用shutil stdlib模块。

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)

如果要按文件名复制,可以执行以下操作:

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)