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

标签 python python-3.x file file-io binaryfiles

我在 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/

相关文章:

python - 分组后计算数据框中某些值的数量

Python 装饰器无法访问被调用的方法

c# - 临时文件保存的时间长度?

ruby-on-rails - 下载大文件(~40MB)并使用回形针另存为附件

file - 如何在 Elixir(或 Erlang)中读取文件的一部分?

python - 在 zappa 中调度 lambda 函数来停止实例

python - 使用 AND 条件查询单行 DataFrame

python - Google App Engine URL 处理程序运行时出错

python-3.x - df.columns.tolist() 返回字符串而不是元组

python-3.x - 如何将 slider 添加到 altair 中的等值线?