问题:Python将字节写入文件

我有一个返回字符串的函数。该字符串包含回车符和换行符(0x0D,0x0A)。但是,当我写入文件时,它仅包含换行符。有没有一种方法可以使输出包括回车和换行符。

msg = function(arg1, arg2, arg3)
f = open('/tmp/output', 'w')
f.write(msg)
f.close()

I have a function that returns a string. The string contains carriage returns and new line feeds (0x0D, 0x0A). However when I write to a file it contains only the new line feeds. Is there a way to get the output to include the carriage return and the new line feed.

msg = function(arg1, arg2, arg3)
f = open('/tmp/output', 'w')
f.write(msg)
f.close()

回答 0

如果要写入字节,则应以二进制模式打开文件。

f = open('/tmp/output', 'wb')

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。