[英]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.