Issue
I use a PC at home and a Mac at work. I've never had any problems with line breaks in python script or their outputs, but whenever i send something to my boss i get an angry e-mail back about windows line breaks in it.
The most recent was the output of a python script where i'd told it to end every line with '\n', but on closer inspection (on my Mac at work) it seems that each line did in fact end with '\r\n'.
What's going on, and how do i stop it? I used to run all my scripts in a Linux virtual machine at home, but i found that was too slow and fiddly, surely there's a simpler fix?
Solution
This is because you have files opened in text mode and Python is normalizing the newlines in accordance with the platform you're using (Windows used \r\n
and Linux just uses \n
). You need to open files in binary mode like this:
f = open("myfile.txt","wb")
It does the same thing in reverse when you read in files (\r\n
will be replaced by \n
) unless you also specify binary mode:
f = open("myfile.txt", "rb")
Answered By - Thomas Parslow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.