如何确保 filehandle.write() 不会因 str/bytes 转换问题而失败?

发布于 2024-09-16 21:45:29 字数 240 浏览 4 评论 0原文

我需要检测文件句柄是否使用二进制模式或文本模式 - 这是为了能够编码/解码 str/bytes 所必需的。我怎样才能做到这一点?

使用二进制模式时,myfile.write(bytes) 有效,而在文本模式下,myfile.write(str) 有效。

我的想法是,我需要知道这一点,以便能够在调用 myfile.write() 之前对参数进行编码/解码,否则可能会失败并出现异常。

I need to detect if a filehandle is using binary mode or text mode - this is required in order to be able to encode/decode str/bytes. How can I do that?

When using binary mode myfile.write(bytes) works, and when in text mode myfile.write(str) works.

The idea is that I need to know this in order to be able to encode/decode the argument before calling myfile.write(), otherwise it may fail with an exception.

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

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

发布评论

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

评论(2

残月升风 2024-09-23 21:45:29

http://docs.python.org/library/stdtypes.html#file。模式

>>> f = open("blah.txt", "wb")
>>> f
<open file 'blah.txt', mode 'wb' at 0x0000000001E44E00>
>>> f.mode
'wb'
>>> "b" in f.mode
True

有此警告:

文件模式

文件的 I/O 模式。如果文件是使用 open() 创建的
内置函数,这将是
模式参数的值。这是一个
只读属性,可能不是
存在于所有类似文件的对象上。

http://docs.python.org/library/stdtypes.html#file.mode

>>> f = open("blah.txt", "wb")
>>> f
<open file 'blah.txt', mode 'wb' at 0x0000000001E44E00>
>>> f.mode
'wb'
>>> "b" in f.mode
True

With this caveat:

file.mode

The I/O mode for the file. If the file was created using the open()
built-in function, this will be the
value of the mode parameter. This is a
read-only attribute and may not be
present on all file-like objects.

述情 2024-09-23 21:45:29

如何以这种方式解决您的问题:

try:
    f.write(msg)
except TypeError:
    f.write(msg.encode("utf-8"))

即使您的句柄不提供.mode,这也会起作用。

How about solving your problem this way:

try:
    f.write(msg)
except TypeError:
    f.write(msg.encode("utf-8"))

This will work even if your handle does not provide a .mode.

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