简体   繁体   English

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

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

When I write into a text file within a python 2.7 script that runs on Windows the new line delimiter is '\\r\\n' , but I would like it to be '\\n' .当我在 Windows 上运行的 python 2.7 脚本中写入文本文件时,新行分隔符是'\\r\\n' ,但我希望它是'\\n'

I have tried to use open with newline='\\n' , but it raised an exception.我曾尝试将opennewline='\\n' ,但它引发了异常。

import io
f= io.open("myfile.txt", "w", newline="\n")
f.write(”aaaaaaa”)
f.close()

The following works for me and writes using \\n instead of \\r\\n以下内容适用于我并使用\\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()

If you use open("file.ext", "wb") to open the file in binary mode, you will have your desired behavior.如果您使用open("file.ext", "wb")以二进制模式打开文件,您将获得所需的行为。 The conversion of "\\n" to "\\r\\n" is only done: "\\n""\\r\\n"的转换只完成:

  • if you're on Windows and如果您使用的是 Windows 并且
  • open your file in text mode, ie open("file.ext", "w")以文本模式打开文件,即open("file.ext", "w")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM