Python将字节写入文件

问题: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')