簡體   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