gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:13 25 4
gpt4 key购买 nike

我需要检测文件句柄是使用二进制模式还是文本模式——这是为了能够编码/解码 str/bytes 所必需的。我该怎么做?

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

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

最佳答案

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

有这个警告:

file.mode

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

关于python - 如何确保 filehandle.write() 不会因 str/bytes 转换问题而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com