Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to write text files with DOS line endings on linux

Tags:

I want to write text files with DOS/Windows line endings '\r\n' using python running on Linux. It seems to me that there must be a better way than manually putting a '\r\n' at the end of every line or using a line ending conversion utility. Ideally I would like to be able to do something like assign to os.linesep the separator that I want to use when writing the file. Or specify the line separator when I open the file.

like image 464
gaumann Avatar asked Apr 15 '10 00:04

gaumann


People also ask

How do you write to a file line by line in Python?

To write line by line to a csv file in Python, use either file. write() function or csv. writer() function. The csv.

What line endings does Linux use?

Back to line endings The reasons don't matter: Windows chose the CR/LF model, while Linux uses the \n model. So, when you create a file on one system and use it on the other, hilarity ensues.

What are DOS line endings?

Text files created on DOS/Windows machines have different line endings than files created on Unix/Linux. DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n").


1 Answers

For Python 2.6 and later, the open function in the io module has an optional newline parameter that lets you specify which newlines you want to use.

For example:

import io with io.open('tmpfile', 'w', newline='\r\n') as f:     f.write(u'foo\nbar\nbaz\n') 

will create a file that contains this:

foo\r\n bar\r\n baz\r\n 
like image 101
gaumann Avatar answered Oct 26 '22 08:10

gaumann