Python - shutil似乎没有制作文件的真正二进制副本

Jay*_*Jay 1 python copy shutil

根据昨天海报的精彩建议,我开始使用该shutil.copyfileobj方法制作文件的副本.

我的程序应该制作文件的精确副本,删除最后一个字节并保存新副本.

我昨晚用一些非常小的ASCII文本文件对它进行了测试,所以我可以检查它是否按照我的要求进行操作,今天早上我尝试了一些实际的"复杂"文件,PDF和JPG,看起来像副本功能不是真正的副本.我在十六进制编辑器中查看了生成的文件,我可以看到在偏移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)
Run Code Online (Sandbox Code Playgroud)

我还可以看到新创建的对象明显小于源文件.

Fre*_*Foo 6

正如您已经注意到的,您应该以二进制模式打开文件; open(srcfile, "rb")open(destfile, "wb+").否则,Python将假定文件是文本文件,并且可能会进行换行,具体取决于平台(有关详细信息,请参阅教程).