簡體   English   中英

Python 2.7:如何在 Windows 上將新行的分隔符限制為“\\n”?

[英]Python 2.7 : How to constrain the delimiter of a new line to be '\n' on Windows?

當我在 Windows 上運行的 python 2.7 腳本中寫入文本文件時,新行分隔符是'\\r\\n' ,但我希望它是'\\n'

我曾嘗試將opennewline='\\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"的轉換只完成:

  • 如果您使用的是 Windows 並且
  • 以文本模式打開文件,即open("file.ext", "w")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM