繁体   English   中英

如何使用Python 3将文本写入以二进制模式打开的文件中?

[英]How to write text into a file opened in binary mode using Python 3?

我在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)。

上面的代码出了什么问题? 将文本写入以二进制模式打开的文件的正确方法是什么?

print()对传递给它的对象做了一些事情。 避免将其用于二进制数据。

f.write(b'foo\nbar\n')

您不需要二进制模式。 打开文件时指定换行符。 默认为通用换行模式,它将换行符转换为平台默认值。 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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM