Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Unix end of line characters in Windows?

Tags:

python

newline

How can I write to files using Python (on Windows) and use the Unix end of line character?

e.g. When doing:

 f = open('file.txt', 'w') f.write('hello\n') f.close() 

Python automatically replaces \n with \r\n.

like image 978
tttppp Avatar asked Mar 29 '10 08:03

tttppp


People also ask

Can Windows use Unix line endings?

Starting with the current Windows 10 Insider build, Notepad will support Unix/Linux line endings (LF), Macintosh line endings (CR), and Windows Line endings (CRLF) as usual.

How do I change Unix line endings in Windows?

Converting using Notepad++ To write your file in this way, while you have the file open, go to the Edit menu, select the "EOL Conversion" submenu, and from the options that come up select "UNIX/OSX Format". The next time you save the file, its line endings will, all going well, be saved with UNIX-style line endings.

How can I see end of line characters in Windows?

use a text editor like notepad++ that can help you with understanding the line ends. It will show you the line end formats used as either Unix(LF) or Macintosh(CR) or Windows(CR LF) on the task bar of the tool. you can also go to View->Show Symbol->Show End Of Line to display the line ends as LF/ CR LF/CR.

How do I find the end of a line character in Unix?

Try file -k It will output with CRLF line endings for DOS/Windows line endings. It will output with CR line endings for MAC line endings. And for Linux/Unix line "LF" it will just output text .


1 Answers

The modern way: use newline=''

Use the newline= keyword parameter to io.open() to use Unix-style LF end-of-line terminators:

import io f = io.open('file.txt', 'w', newline='\n') 

This works in Python 2.6+. In Python 3 you could also use the builtin open() function's newline= parameter instead of io.open().

The old way: binary mode

The old way to prevent newline conversion, which does not work in Python 3, is to open the file in binary mode to prevent the translation of end-of-line characters:

f = open('file.txt', 'wb')    # note the 'b' meaning binary 

but in Python 3, binary mode will read bytes and not characters so it won't do what you want. You'll probably get exceptions when you try to do string I/O on the stream. (e.g. "TypeError: 'str' does not support the buffer interface").

like image 124
Colin D Bennett Avatar answered Oct 24 '22 19:10

Colin D Bennett