Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write native newline character to a file descriptor in Python?

Tags:

python

The os.write function can be used to writes bytes into a file descriptor (not file object). If I execute os.write(fd, '\n'), only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux.
What is the best way to achieve this?

I'm using Python 2.6, but I'm also wondering if Python 3 has a different solution.

like image 815
hcs42 Avatar asked Aug 03 '09 16:08

hcs42


People also ask

How do you add a new line to a string in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

Do new lines matter in Python?

Unlike in SQL, in Python, line breaks matter. Which means that in 99% of cases, if you put a line break where you shouldn't put one, you will get an error message.

What is OS Linesep?

The os. linesep indicates the character used by the operating system to terminate lines. The value for os. linesep is \n for POSIX and \r\n for Windows.


2 Answers

Use this

import os os.write(fd, os.linesep) 
like image 114
S.Lott Avatar answered Sep 25 '22 03:09

S.Lott


How about os.write(<file descriptor>, os.linesep)? (import os is unnecessary because you seem to have already imported it, otherwise you'd be getting errors using os.write to begin with.)

like image 29
JAB Avatar answered Sep 23 '22 03:09

JAB