一次读取整个文件

时间:2013-10-08 15:18:11

标签: python file-io

我需要从文件中读取整个源数据.zip(不解压缩)

我试过

f = open('file.zip')
s = f.read()
f.close()
return s

但它只返回几个字节而不是整个源数据。知道如何实现它吗?谢谢

3 个答案:

答案 0 :(得分:25)

在处理二进制文件时使用二进制模式(b)。

def read_zipfile(path):
    with open(path, 'rb') as f:
        return f.read()

顺便说一句,请使用with statement代替手动close

答案 1 :(得分:4)

如上所述,有一个EOF字符(0x1A)终止.read()操作。重现这一点并证明:

# 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

答案 2 :(得分:2)

这应该这样做:

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*