Skip to main content
 首页 » 编程设计

python之在python中读取文件

2025年05月04日12leader

试图了解您应该如何在 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 

输出:

The real filesize is 183574528 
The read filesize is 10322 
this time it's 13440 

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

请您参考如下方法:

如果您的文件混淆了 C 库,那么您的结果是意料之中的。

操作系统认为它是 180Mb。

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

尝试用“rb”打开文件,看看是否会得到不同的结果。