如何在Python中复制文件?
当前回答
Python提供了内置函数,可以使用操作系统shell实用程序轻松复制文件。
以下命令用于复制文件:
shutil.copy(src, dst)
以下命令用于复制包含元数据信息的文件:
shutil.copystat(src, dst)
其他回答
首先,我对shutil方法做了详尽的备忘单,供您参考。
shutil_methods =
{'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
}
其次,举例说明复制方法:
shutil.copyfileobj(fsrc,fdst[,length])操纵打开的对象在[3]中:src='~/Documents/Head+First+SQL.pdf'在[4]中:dst='~/desktop'在[5]中:shutil.copyfileobj(src,dst)AttributeError:“str”对象没有属性“read”#复制文件对象在[7]中:open(src,'rb')为f1,open(os.path.join(dst,'test.pdf'),'wb')为f2:…:shutil.copyfileobj(f1,f2)在[8]中:os.stat(os.path.join(dst,'test.pdf'))输出[8]:os.stat_result(st_mode=33188,st_ino=8598319475,st_dev=16777220,st_nlink=1,st_uid=501,st_gid=20,st_size=13507926,st_atime=1516067347,st_mime=1516067335,st_ctime=1516087345)shutil.copyfile(src,dst,*,follow_symlinks=True)复制并重命名在[9]中:shutil.copyfile(src,dst)IsADirectoryError:[Erno 21]是一个目录:~/desktop'#所以dst应该是文件名而不是目录名shutil.copy()复制而不预先保存元数据在[10]中:shutil.copy(src,dst)输出[10]:~/desktop/Head+First+SQL.pdf'#检查其元数据在[25]中:os.stat(src)输出[25]:os.stat_result(st_mode=33188,st_ino=597749,st_dev=16777220,st_nlink=1,st_uid=501,st_gid=20,st_size=13507926,st_atime=1516066425,st_mtime=1493698739,st_ctime=1514871215)在[26]中:os.stat(os.path.join(dst,'Head+First+SQL.pdf'))输出[26]:os.stat_result(st_mode=33188,st_ino=8598313736,st_dev=16777220,st_nlink=1,st_uid=501,st_gid=20,st_size=13507926,st_atime=1516066427,st_mtime=1516086425,st_ctime=151066425)#st_atime、st_mtime、st_ctime已更改shutil.copy2()复制并保留元数据在[30]中:shutil.copy2(src,dst)输出[30]:~/desktop/Head+First+SQL.pdf'在[31]中:os.stat(src)输出[31]:os.stat_result(st_mode=33188,st_ino=597749,st_dev=16777220,st_nlink=1,st_uid=501,st_gid=20,st_size=13507926,st_atime=1516067055,st_mtime=1493698739,st_ctime=1514871215)在[32]中:os.stat(os.path.join(dst,'Head+First+SQL.pdf'))输出[32]:os.stat_result(st_mode=33188,st_ino=8598313736,st_dev=16777220,st_nlink=1,st_uid=501,st_gid=20,st_size=13507926,st_atime=1516067063,st_mtime=1493698739,st_ctime=1516087055)#保留时间(_m)shutil.copytree()递归复制以src为根的整个目录树,返回目标目录。
与公认的答案类似,如果您还想确保在目标路径中创建任何(不存在的)文件夹,以下代码块可能会很有用。
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):可能会很有用。
这是一个利用“shutil.copyfileobj”的答案,它非常高效。我在不久前创建的一个工具中使用了它。我最初没有写这篇文章,但我稍微修改了一下。
def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):
'''
@param src: Source File
@param dst: Destination File (not file path)
@param buffer_size: Buffer size to use during copy
@param perserveFileDate: Preserve the original file date
'''
# Check to make sure destination directory exists. If it doesn't create the directory
dstParent, dstFileName = os.path.split(dst)
if(not(os.path.exists(dstParent))):
os.makedirs(dstParent)
# Optimize the buffer for small files
buffer_size = min(buffer_size,os.path.getsize(src))
if(buffer_size == 0):
buffer_size = 1024
if shutil._samefile(src, dst):
raise shutil.Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if shutil.stat.S_ISFIFO(st.st_mode):
raise shutil.SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
shutil.copyfileobj(fsrc, fdst, buffer_size)
if(perserveFileDate):
shutil.copystat(src, dst)
万一你走得这么远。答案是您需要整个路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
有两种在Python中复制文件的最佳方法。
1.我们可以使用梭动模块
代码示例:
import shutil
shutil.copyfile('/path/to/file', '/path/to/new/file')
除了copyfile,还有其他可用的方法,如copy、copy2等,但copyfile在性能方面是最好的,
2.我们可以使用OS模块
代码示例:
import os
os.system('cp /path/to/file /path/to/new/file')
另一种方法是使用子流程,但它不是优选的,因为它是调用方法之一,不安全。