[英]Missing bytes in Python when writing binary files?
When writing binary files in Python I seem to be missing some bytes.在 Python 中写入二进制文件时,我似乎缺少一些字节。 I've tried this with the "write" function and with the "array.tofile" function.
我已经用“write” function 和“array.tofile” function 试过这个。 Here is some example code:
这是一些示例代码:
import zlib, sys, os, array
from struct import unpack
from array import array
inputFile = 'strings.exe'
print "Reading data from: ", inputFile
print 'Input File Size:', os.path.getsize(inputFile)
f = open(inputFile, 'rb')
#compressedDocument =
document = f.read()
documentArray = array('c', document)
print 'Document Size:', len(documentArray)
copyFile = open( 'Copy of ' + inputFile, 'wb')
documentArray.tofile(copyFile)
#copyFile.write(document)
copyFile.close
print 'Output File Size:', os.path.getsize('Copy of ' + inputFile)
print 'Missing Bytes:', os.path.getsize(inputFile) - os.path.getsize('Copy of ' + inputFile)
f.close()
Gives the following output:给出以下 output:
Reading data from: strings.exe
Input File Size: 136592
Document Size: 136592
Output File Size: 135168
Missing Bytes: 1424
I don't understand why those bytes aren't being written.我不明白为什么没有写入这些字节。 I've tried this on multiple files with a varying number of missing bytes.
我已经在具有不同数量的缺失字节的多个文件上尝试过这个。
You are not closing your output file before you call os.path.getsize
on it .在调用
os.path.getsize
之前,您不会关闭 output 文件。 Your 135168 bytes written is 33 x 4096 byte blocks... try copyFile.close()
instead of copyFile.close
.您写入的 135168 字节是 33 x 4096 字节块...尝试
copyFile.close()
而不是copyFile.close
。
If you actually try to compare the two binary files (if you are under unix you use the cmp
command) you will see the two files are identical.如果您实际上尝试比较两个二进制文件(如果您在 unix 下使用
cmp
命令),您将看到两个文件是相同的。
EDIT: As correctly pointed out by John in his answer, the difference in byte size is due to not closing the file before measuring its length.编辑:正如约翰在他的回答中正确指出的那样,字节大小的差异是由于在测量文件长度之前没有关闭文件。 The correct line in the code should be
copyFile.close()
[invoking the method] instead of copyFile.close
[which is the method object].代码中的正确行应该是
copyFile.close()
[调用方法] 而不是copyFile.close
[这是方法对象]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.