我似乎得到不同的輸出:StringIO與二進制文件?
from StringIO import *
file = open('1.bmp', 'r')
print file.read(), '\n'
print StringIO(file.read()).getvalue()
爲什麼?是否因爲StringIO僅支持文本字符串或其他?
我似乎得到不同的輸出:StringIO與二進制文件?
from StringIO import *
file = open('1.bmp', 'r')
print file.read(), '\n'
print StringIO(file.read()).getvalue()
爲什麼?是否因爲StringIO僅支持文本字符串或其他?
當您撥打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')
你不應該使用"rb"
來打開,而不是僅僅使用"r"
,因爲這種模式假定你將只處理ASCII字符和EOF?
在某些平臺上(以及Python 3中的任何地方),只需'r'就表示二進制模式。另外,請勿在您的帖子中添加標語/簽名。 – agf
第二個file.read()
實際上只返回一個空字符串。您應該執行file.seek(0)
以倒轉內部文件偏移量。
使用該代碼,第二個file.read()將不會得到任何結果。您應該再次讀取文件之前使用seek(0)。 –