根据昨天一张海报的精彩建议,我开始使用shutil.copyfileobj
方法复制一个文件。在
我的程序应该制作文件的精确副本,删除最后一个字节并保存新副本。在
我昨晚用一些非常小的ASCII文本文件测试了它,这样我就可以检查它是否执行了我要求的操作,今天早上我已经在一些实际的“复杂”文件上尝试过,一个PDF和一个JPG,看起来复制功能并不是真的复制。我在十六进制编辑器中查看了结果文件,可以看到在~offset 0x300之后出现了一些奇怪的情况—要么添加了数据,要么在复制时更改了数据。我不知道是哪个。在
我的程序迭代地删除一个字节并保存一个新版本,我可以看到新创建的文件与原始文件完全不同(最后一个字节除外)
def doNibbleAndSave(srcfile,fileStripped,strippedExt,newpath):
counter = '%(interationCounter)03d' % {"interationCounter":interationCounter} #creates the filename counter lable
destfile = newpath + "\\" + fileStripped + "_" + counter + strippedExt #creates the new filename
with open(srcfile, 'r') as fsrc:
with open(destfile, 'w+') as fdest:
shutil.copyfileobj(fsrc, fdest)
fdest.seek(nibbleSize, os.SEEK_END) #sets the number of bytes to be removed
fdest.truncate()
srcfile = destfile #makes the iterator pick up the newly 'nibbled' file to work on next
return (srcfile)
我还可以看到新创建的对象明显小于源文件。在
正如您已经注意到的,应该以二进制模式打开文件;
open(srcfile, "rb")
和open(destfile, "wb+")
。否则,Python将假定这些文件是文本文件,并可能根据平台进行换行转换(有关详细信息,请参见the tutorial)。在相关问题 更多 >
编程相关推荐