如何在Python中复制文件?


当前回答

Use

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

以读取模式打开源文件,以写入模式写入目标文件。

其他回答

对于小文件和仅使用Python内置程序,可以使用以下一行代码:

with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())

对于文件太大或内存很关键的应用程序来说,这不是最佳方式,因此应该首选Swati的答案。

Python提供了内置函数,可以使用操作系统shell实用程序轻松复制文件。

以下命令用于复制文件:

shutil.copy(src, dst)

以下命令用于复制包含元数据信息的文件:

shutil.copystat(src, dst)

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

import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)  # dst can be a folder; use shutil.copy2() to preserve timestamp

将名为src的文件的内容复制到名为dst的文件中。src和dst都需要是文件的整个文件名,包括路径。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,则将替换它。无法使用此功能复制字符或块设备和管道等特殊文件。对于copy,src和dst是作为strs给出的路径名。

另一个shutil方法是shutil.copy2()。它类似,但保留了更多的元数据(例如时间戳)。

如果使用os.path操作,请使用copy而不是copyfile。copyfile将只接受字符串。

这里有一个简单的方法,不需要任何模块。这与这个答案类似,但如果它是一个不适合RAM的大文件,那么它也可以工作:

with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:
    while True:
        block = f.read(16*1024*1024)  # work by blocks of 16 MB
        if not block:  # end of file
            break
        g.write(block)

因为我们正在编写一个新文件,所以它不会保留修改时间等。如果需要,我们可以使用os.utime。

您可以使用shutil软件包中的复制功能之一:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata  
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy              ✔             ✔                 ☐           ☐
shutil.copy2             ✔             ✔                 ☐           ✔
shutil.copyfile          ☐             ☐                 ☐           ☐
shutil.copyfileobj       ☐             ☐                 ✔           ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

例子:

import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')