我需要从文件 something.zip 中读取整个源数据(不要解压缩)
我试过
f = open('file.zip')
s = f.read()
f.close()
return s
但它只返回几个字节而不是整个源数据。知道如何实现吗?谢谢
b
处理二进制文件时使用二进制模式( )。
def read_zipfile(path):
with open(path, 'rb') as f:
return f.read()
顺便说一句,使用with
statement而不是 manual close
。
如前所述,有一个0x1A
终止.read()
操作的 EOF 字符 ( )。要重现这一点并演示:
# Create file of 256 bytes
with open('testfile', 'wb') as fout:
fout.write(''.join(map(chr, range(256))))
# Text mode
with open('testfile') as fin:
print 'Opened in text mode is:', len(fin.read())
# Opened in text mode is: 26
# Binary mode - note 'rb'
with open('testfile', 'rb') as fin:
print 'Opened in binary mode is:', len(fin.read())
# Opened in binary mode is: 256
这应该这样做:
In [1]: f = open('/usr/bin/ping', 'rb')
In [2]: bytes = f.read()
In [3]: len(bytes)
Out[3]: 9728
为了比较,这是我在上面的代码中打开的文件:
-rwx------+ 1 xx yy 9.5K Jan 19 2005 /usr/bin/ping*