如何确保 filehandle.write() 不会因 str/bytes 转换问题而失败?
我需要检测文件句柄是否使用二进制模式或文本模式 - 这是为了能够编码/解码 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://docs.python.org/library/stdtypes.html#file。模式
有此警告:
http://docs.python.org/library/stdtypes.html#file.mode
With this caveat:
如何以这种方式解决您的问题:
即使您的句柄不提供
.mode
,这也会起作用。How about solving your problem this way:
This will work even if your handle does not provide a
.mode
.