简体   繁体   English

如何使 Python 中的 file.write() 方法显式写入换行符?

[英]How to make the file.write() method in Python explicitly write the newline characters?

I am trying to write text to an output file that explicitly shows all of the newline characters ( \n , \r , \r\n ,).我正在尝试将文本写入明确显示所有换行符( \n\r\r\n )的输出文件。 I am using Python 3 and Windows 7. My thought was to do this by converting the strings that I am writing into bytes.我正在使用 Python 3 和 Windows 7。我的想法是通过将我正在写入的字符串转换为字节来做到这一点。

My code looks like this:我的代码如下所示:

file_object = open(r'C:\Users\me\output.txt', 'wb')`
for line in lines:
    line = bytes(line, 'UTF-8')  
    print('Line: ', line)   #for debugging
    file_object.write(line)
file_object.close()

The print( ) statement to standard output (my Windows terminal) is as I want it to be.标准输出(我的 Windows 终端)的print( ) 语句是我想要的。 For example, one line looks like so, with the \n character visible.例如,一行看起来像这样, \n字符可见。

Line: b'<p class="byline">Foo C. Bar</p>\n'

However, the write() method does not explicitly print any of the newline characters in my output.txt file.但是, write()方法不会在我的 output.txt 文件中显式打印任何换行符。 Why does write() not explicitly show the newline characters in my output text file, even though I'm writing in bytes mode, but print does explicitly show the newline characters in the windows terminal?为什么write()没有在我的输出文本文件中显式显示换行符,即使我在字节模式下写入,但print确实在 Windows 终端中显式显示换行符?

What Python does when writing strings or bytes to text or binary files: Python 在将字符串或字节写入文本或二进制文件时会做什么:

  • Strings to a text file.文本文件的字符串。 Directly written.直接写的。
  • Bytes to a text file.字节到文本文件。 Writes the repr .写入repr
  • Strings to a binary file.二进制文件的字符串。 Throws an exception.引发异常。
  • Bytes to a binary file.字节到二进制文件。 Directly written.直接写的。

You say that you get what you're looking for when you write a bytes to standard out (a text file).您说当您将bytes写入标准输出(文本文件)时,您得到了您正在寻找的东西。 That, with the pseudo-table above, suggests you might look into using repr .上面的伪表表明您可能会考虑使用repr Specifically, if you're looking for the output b'<p class="byline">Foo C. Bar</p>\n' , you're looking for the repr of a bytes object.具体来说,如果您正在寻找输出b'<p class="byline">Foo C. Bar</p>\n' ,那么您正在寻找bytes对象的repr If line was a str to start with and you don't actually need that b at the beginning, you might instead be looking for the repr of the string, '<p class="byline">Foo C. Bar</p>\n' .如果line是一个str开头,而你实际上并不需要那个b开头,你可能会寻找字符串的repr'<p class="byline">Foo C. Bar</p>\n' If so, you could write it like this:如果是这样,你可以这样写:

with open(r'C:\Users\me\output.txt', 'w') as file_object:
    for line in lines:
        file_object.write(repr(line) + '\n')

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

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