我在 Windows 7 上使用 Python 3.5.1 运行以下代码。
with open('foo.txt', 'wb') as f:
print(b'foo\nbar\n', file=f)
我收到以下错误。
Traceback (most recent call last):
File "foo.py", line 2, in <module>
print(b'foo\nbar\n', file=f)
TypeError: a bytes-like object is required, not 'str'
我的目的是在文件中写入文本,以便所有 '\n'
在文件中显示为 LF(而不是 CRLF)。
我上面的代码有什么问题?将文本写入以二进制模式打开的文件中的正确方法是什么?
最佳答案
您不需要二进制模式。打开文件时指定换行符。默认是通用换行模式,它将换行符转换为平台默认值或从平台默认值转换换行符。 newline=''
或 newline='\n'
指定未翻译模式:
with open('foo.txt', 'w', newline='\n') as f:
print('foo', file=f)
print('bar', file=f)
with open('bar.txt', 'w', newline='\r') as f:
print('foo', file=f)
print('bar', file=f)
with open('foo.txt','rb') as f:
print(f.read())
with open('bar.txt','rb') as f:
print(f.read())
输出(在 Windows 上):
b'foo\nbar\n'
b'foo\rbar\r'
关于python - 如何使用 Python 3 将文本写入以二进制模式打开的文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36466816/