如何在Python中复制文件?
当前回答
使用subprocess.call复制文件
from subprocess import call
call("cp -p <file> <file>", shell=True)
其他回答
使用梭动模块。
copyfile(src, dst)
将名为src的文件的内容复制到名为dst的文件中。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,则将替换它。无法使用此功能复制字符或块设备和管道等特殊文件。src和dst是以字符串形式给出的路径名。
看看标准Python模块中所有文件和目录处理功能的filesys。
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模块提供了一些对文件的高级操作。它支持文件复制和删除。
请参考下表了解您的用例。
Function | Utilize File Object |
Preserve File Metadata |
Preserve Permissions |
Supports Directory Dest. |
---|---|---|---|---|
shutil.copyfileobj | ✔ | ⅹ | ⅹ | ⅹ |
shutil.copyfile | ⅹ | ⅹ | ⅹ | ⅹ |
shutil.copy2 | ⅹ | ✔ | ✔ | ✔ |
shutil.copy | ⅹ | ⅹ | ✔ | ✔ |
与公认的答案类似,如果您还想确保在目标路径中创建任何(不存在的)文件夹,以下代码块可能会很有用。
from os import path, makedirs
from shutil import copyfile
makedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)
copyfile(source_path, destination_path)
正如公认的答案所指出的,这些行将覆盖目标路径上存在的任何文件,因此有时在该代码块之前添加:if not path.exists(destination_path):可能会很有用。
使用subprocess.call复制文件
from subprocess import call
call("cp -p <file> <file>", shell=True)