Joe*_*lmc 5 python string file stringio
我似乎得到了不同的输出:
from StringIO import *
file = open('1.bmp', 'r')
print file.read(), '\n'
print StringIO(file.read()).getvalue()
Run Code Online (Sandbox Code Playgroud)
为什么?是因为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()
Run Code Online (Sandbox Code Playgroud)
您还可以使用该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()
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我建议以二进制模式打开二进制文件: open('1.bmp', 'rb')
归档时间: |
|
查看次数: |
10331 次 |
最近记录: |