2011-11-18 35 views
0

我有两个二进制输入文件,firstfilesecondfilesecondfilefirstfile +其他材料。我想在一个单独的文件中分离这些附加材料,newfile。这是我到目前为止有:使用Python分割和编写二进制文件

import os 
import struct 

origbytes = os.path.getsize(firstfile) 
fullbytes = os.path.getsize(secondfile) 
numbytes = fullbytes-origbytes 

with open(secondfile,'rb') as f: 
    first = f.read(origbytes) 
    rest = f.read() 

当然,我的倾向是做(这似乎工作):

with open(newfile,'wb') as f: 
    f.write(rest) 

我无法找到它,但以为我读了,让我在写入文件之前,应使用struct.pack将其首先打包。下面给我一个错误:

with open(newfile,'wb') as f: 
    f.write(struct.pack('%%%ds' % numbytes,rest)) 

-----> error: bad char in struct format 

但是这工作:

with open(newfile,'wb') as f: 
    f.write(struct.pack('c'*numbytes,*rest)) 

而且对于工作的人,这给了我正确的答案

with open(newfile,'rb') as f: 
    test = f.read() 

len(test)==numbytes 

-----> True 

这是正确的方法写一个二进制文件?我只是想确保我正确地执行这部分来诊断文件的第二部分是否已损坏,因为我正在向newfile提供的另一个读取器程序告诉我,或者我做错了。谢谢。

回答

2

没有理由使用struct模块,该模块用于在二进制格式和Python对象之间进行转换。这里不需要转换。

Python 2.x中的字符串只是一个字节数组,可以在文件中读写。 (在Python 3中。,X,读函数返回一个bytes对象,这是同样的事情,如果你打开该文件open(filename, 'rb')

所以,你可以只读取文件转换成字符串,然后再写一遍:

import os 

origbytes = os.path.getsize(firstfile) 
fullbytes = os.path.getsize(secondfile) 
numbytes = fullbytes-origbytes 

with open(secondfile,'rb') as f: 
    first = f.seek(origbytes) 
    rest = f.read() 

with open(newfile,'wb') as f: 
    f.write(rest) 
+0

感谢您澄清'struct'的使用。 – hatmatrix

0

这不是c,格式字符串中没有%。你想要的是:

f.write(struct.pack('%ds' % numbytes,rest)) 

它的工作对我来说:

>>> struct.pack('%ds' % 5,'abcde') 
'abcde' 

说明:'%%%ds' % 15'%15s',而你想要的是'%ds' % 15这是'15s'

+0

啊,对,谢谢 - 但是你知道这是否是正确的方法来分割二进制文件吗? – hatmatrix

+0

@crippledlambda不知道,但它听起来好像会起作用,只要第二个文件只是第一个在末尾有更多数据。 –

+0

非常感谢! – hatmatrix

3

如果你知道secondfile是与firstfile +附加数据相同,为什么即使读取第二个文件的第一部分?

with open(secondfile,'rb') as f: 
    f.seek(origbytes) 
    rest = f.read() 

至于写出来的东西,

with open(newfile,'wb') as f: 
    f.write(rest) 

就好了。无论如何,与struct的东西将只是一个没有操作。您可能会考虑的唯一的事情是rest的大小。如果它可能很大,您可能需要读取和写入数据块。

1
  1. 你并不需要阅读origbytes,只需将文件指针到合适的位置:f.seek(numbytes)
  2. 你不需要struct包装,写restnewfile