2011-09-26 155 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)以倒轉內部文件偏移量。