I am trying to write text to an output file that explicitly shows all of the newline characters ( \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.
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. For example, one line looks like so, with the \n
character visible.
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. 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?
What Python does when writing strings or bytes to text or binary files:
repr
. You say that you get what you're looking for when you write a bytes
to standard out (a text file). That, with the pseudo-table above, suggests you might look into using 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. 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'
. 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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.