StringIO 与二进制文件?

发布于 2024-12-06 14:02:59 字数 197 浏览 1 评论 0原文

我似乎得到了不同的输出:

from StringIO import *

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

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

为什么?是不是因为StringIO只支持文本字符串什么的?

I seem to get different outputs:

from StringIO import *

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

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

Why? Is it because StringIO only supports text strings or something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花落人断肠 2024-12-13 14:02:59

当您调用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')

When you call file.read(), it will read the entire file into memory. Then, if you call file.read() again on the same file object, it will already have reached the end of the file, so it will only return an empty string.

Instead, try e.g. reopening the file:

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()

You can also use the with statement to make that code cleaner:

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()

As an aside, I would recommend opening binary files in binary mode: open('1.bmp', 'rb')

小红帽 2024-12-13 14:02:59

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

The second file.read() actually returns just an empty string. You should do file.seek(0) to rewind the internal file offset.

帝王念 2024-12-13 14:02:59

难道您不应该使用 "rb" 打开,而不仅仅是 "r",因为此模式假定您仅处理 ASCII 字符和 EOF?

Shouldn't you be using "rb" to open, instead of just "r", since this mode assumes that you'll be processing only ASCII characters and EOFs?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文