如何在Python中复制文件?


当前回答

使用subprocess.call复制文件

from subprocess import call
call("cp -p <file> <file>", shell=True)

其他回答

使用subprocess.call复制文件

from subprocess import call
call("cp -p <file> <file>", shell=True)

Use

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

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

万一你走得这么远。答案是您需要整个路径和文件名

import os

shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
Function Copies
metadata
Copies
permissions
Uses file object Destination
may be directory
shutil.copy No Yes No Yes
shutil.copyfile No No No No
shutil.copy2 Yes Yes No Yes
shutil.copyfileobj No No Yes No

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将只接受字符串。