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.
To write line by line to a csv file in Python, use either file. write() function or csv. writer() function. The csv.
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.
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").
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With