Python 一次读取整个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19251736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:15:00  来源:igfitidea点击:

read whole file at once

pythonfile-io

提问by peter

I need to read whole source data from file something.zip (not uncompress it)

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

I tried

我试过

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

but it returns only few bytes and not whole source data. Any idea how to achieve it? Thanks

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

采纳答案by falsetru

Use binary mode(b) when you're dealing with binary file.

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

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

BTW, use withstatementinstead of manual close.

顺便说一句,使用withstatement而不是 manual close

回答by AlG

This should do it:

这应该这样做:

In [1]: f = open('/usr/bin/ping', 'rb')   

In [2]: bytes = f.read()

In [3]: len(bytes)
Out[3]: 9728

For comparison, here's the file I opened in the code above:

为了比较,这里是我在上面的代码中打开的文件:

-rwx------+ 1 xx yy 9.5K Jan 19  2005 /usr/bin/ping*

回答by Jon Clements

As mentioned there is an EOF character (0x1A) that terminates the .read()operation. To reproduce this and demonstrate:

如前所述,有一个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