如何在Python中复制文件?
当前回答
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 |
其他回答
与公认的答案类似,如果您还想确保在目标路径中创建任何(不存在的)文件夹,以下代码块可能会很有用。
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):可能会很有用。
复制文件是一个相对简单的操作,如下面的示例所示,但是您应该使用shutilstdlib模块。
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)
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 |
您可以使用os.link创建文件的硬链接:
os.link(source, dest)
这不是一个独立的克隆,但是如果您计划只读取(而不是修改)新文件,并且其内容必须保持与原始文件相同,那么这将很好地工作。它还有一个好处,如果你想检查副本是否已经存在,你可以比较硬链接(与os.stat)而不是它们的内容。
在Linux中,命令cp带有键
cp -al
创建硬链接。因此,硬链接可被视为副本。有时,一个人需要完全这种行为(从不同的地方访问文件内容),而不需要单独的副本。
shutil模块提供了一些对文件的高级操作。它支持文件复制和删除。
请参考下表了解您的用例。
Function | Utilize File Object |
Preserve File Metadata |
Preserve Permissions |
Supports Directory Dest. |
---|---|---|---|---|
shutil.copyfileobj | ✔ | ⅹ | ⅹ | ⅹ |
shutil.copyfile | ⅹ | ⅹ | ⅹ | ⅹ |
shutil.copy2 | ⅹ | ✔ | ✔ | ✔ |
shutil.copy | ⅹ | ⅹ | ✔ | ✔ |