2011-09-26 129 views
5

我似乎得到不同的输出:StringIO与二进制文件?

from StringIO import * 

file = open('1.bmp', 'r') 

print file.read(), '\n' 
print StringIO(file.read()).getvalue() 

为什么?是否因为StringIO仅支持文本字符串或其他?

+2

使用该代码,第二个file.read()将不会得到任何结果。您应该再次读取文件之前使用seek(0)。 –

回答

8

当您拨打file.read()时,它会将整个文件读入内存。然后,如果您再次在同一个文件对象上调用file.read(),它将已经到达该文件的末尾,因此它只会返回一个空字符串。

而是尝试重新打开文件:

from StringIO import * 

file = open('1.bmp', 'r') 
print file.read(), '\n' 
file.close() 

file2 = open('1.bmp', 'r') 
print StringIO(file2.read()).getvalue() 
file2.close() 

您还可以使用with语句,使代码更清洁:

from StringIO import * 

with open('1.bmp', 'r') as file: 
    print file.read(), '\n' 

with open('1.bmp', 'r') as file2: 
    print StringIO(file2.read()).getvalue() 

顺便说一句,我会建议以二进制方式打开二进制文件:open('1.bmp', 'rb')

+0

是的,你是对的。这并没有完全解决我现实世界的问题,然后我发现我正在'w'模式下写入数据并获取损坏的文件,而不是'wb'。现在一切正常:) – Joelmc

+0

我认为minhee提出的file.seek(0)是一个更好的方法。 – Gallaecio

-1

你不应该使用"rb"来打开,而不是仅仅使用"r",因为这种模式假定你将只处理ASCII字符和EOF?

+0

在某些平台上(以及Python 3中的任何地方),只需'r'就表示二进制模式。另外,请勿在您的帖子中添加标语/签名。 – agf

5

第二个file.read()实际上只返回一个空字符串。您应该执行file.seek(0)以倒转内部文件偏移量。