在python中读取文件

qua*_*ano 1 python file

试图了解你应该如何在python中读取文件.这就是我所做的,它没有正常工作:

import os.path

filename = "A 180 mb large file.data"
size = os.path.getsize(filename)

f = open(filename, "r")
contents = f.read()
f.close()

print "The real filesize is", size
print "The read filesize is", len(contents)

f = open(filename, "r")

size = 0

while True:
    contents = f.read(4)
    if not contents: break
    size += len(contents)

f.close()

print "this time it's", size
Run Code Online (Sandbox Code Playgroud)

输出:

The real filesize is 183574528
The read filesize is 10322
this time it's 13440
Run Code Online (Sandbox Code Playgroud)

有人知道这里发生了什么?:)

S.L*_*ott 5

如果您的文件混淆了C库,那么您的结果是预期的.

操作系统认为它是180Mb.

但是,周围散布着空字节,这可能会混淆C stdio库.

尝试使用"rb"打开文件,看看是否得到不同的结果.