Python newline caveat

Hello Everyone,
This will be a small post about a caveat in Python language (v2.7) for writing output to files.
On Windows the new line character is actually treated as ‘\r\n‘ or CRLF as we know it (Carriage Return followed by a Newline). Sometimes however you may not want to output this newline character into your file and would like a simple ‘\n‘ (newline) character to terminate your line. (Example: when importing data into MySQL or some other relational databases where you do not wish to import this extraneous character as part of the data itself.)

Now, the default mode for line termination in Python 2.7 is to use the underlying Operating System specific character. So when you write the following code, you’ll get a CRLF as the line terminating character:

This will write the output with CRLF character as the line terminator (can be checked with Notepad++).

To prevent your code from running this way, simply change the mode of file to “write binary” by specifying mode as ‘wb‘ instead of simple ‘w’, as shown below:

And lo! this gives the required output with only and LF character ending the statement.

In Python v3, there is a provision within ‘open()‘ function itself to specify the desired newline character by way of named parameter passing. Do check the documentation for the same.

Python newline caveat
Rate this post

Leave a Reply