[英]Python 2.7 : How to constrain the delimiter of a new line to be '\n' on Windows?
當我在 Windows 上運行的 python 2.7 腳本中寫入文本文件時,新行分隔符是'\\r\\n'
,但我希望它是'\\n'
。
我曾嘗試將open
與newline='\\n'
,但它引發了異常。
import io
f= io.open("myfile.txt", "w", newline="\n")
f.write(”aaaaaaa”)
f.close()
以下內容適用於我並使用\\n
而不是\\r\\n
import io
f= io.open("myfile.txt", "w", newline="\n")
#note the io module requires you to write unicode
f.write(unicode("asdasd\nasdasasd\n"))
f.close()
如果您使用open("file.ext", "wb")
以二進制模式打開文件,您將獲得所需的行為。 "\\n"
到"\\r\\n"
的轉換只完成:
open("file.ext", "w")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.