我经常丢失尝试使用shutil copyfile复制的文件的最后几kb。
我做了一些研究,确实看到有人在这里询问类似的问题:python Shutil复制函数缺少最后几行 https://stackoverflow.com/questions/15303555/python-shutil-copy-function-missing-last-few-lines
但我正在使用 copyfile,它似乎使用了 with 语句......
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
所以我很困惑更多的用户没有遇到这个问题,如果确实是某种缓冲问题 - 我认为它会更广为人知。
我非常简单地调用 copyfile,不认为我可能做错了什么,本质上是按照我认为的标准方式进行的:
copyfile(target_file_name,dest_file_name)
但我每次都会丢失文件的最后 4 kb 左右。
我也没有触及在shutil 中调用的copyfile 函数,它是......
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
所以我很茫然,但我想我即将学习一些有关刷新、缓冲或 with 语句的知识,或者......救命!谢谢
对阿南德:
Anand,我避免提及这些东西,因为我感觉这不是问题,但既然你问了...执行摘要是我正在从 FTP 获取一个文件,检查该文件是否与我上次保存的文件不同复制,如果是,则下载该文件并保存副本。这是迂回的意大利面条代码,我猜是在我还是一个真正纯粹的功利主义编码新手时编写的。看起来像:
for filename in ftp.nlst(filematch):
target_file_name = os.path.basename(filename)
with open(target_file_name ,'wb') as fhandle:
try:
ftp.retrbinary('RETR %s' % filename, fhandle.write)
the_files.append(target_file_name)
mtime = modification_date(target_file_name)
mtime_str_for_file = str(mtime)[0:10] + str(mtime)[11:13] + str(mtime)[14:16] + str(mtime)[17:19] + str(mtime)[20:28]#2014-12-11 15:08:00.338415.
sorted_xml_files = [file for file in glob.glob(os.path.join('\\\\Storage\\shared\\', '*.xml'))]
sorted_xml_files.sort(key=os.path.getmtime)
last_file = sorted_xml_files[-1]
file_is_the_same = filecmp.cmp(target_file_name, last_file)
if not file_is_the_same:
print 'File changed!'
copyfile(target_file_name, '\\\\Storage\\shared\\'+'datebreaks'+mtime_str_for_file+'.xml')
else:
print 'File '+ last_file +' hasn\'t changed, doin nothin'
continue