I'm trying to output data to a file using Python.
The following code will break two lines instead of one.
f = open(fileName, "a") f.write(data + os.linesep) f.close()
How can I make a line break for one line?
Python automatically converts
\n to OS-specific line breaks, so using
os.linesep on Windows may result in extra line breaks.
import os with open('hoge.txt', 'w') as f: f.write('hello' + os.linesep) f.write('world!') with open('hoge.txt', 'r') as f: #テキストモードで開く print(f.read()) with open('hoge.txt', 'br') as f: #バイナリモードで開く(改行コードなども表示できる) print(f.read())
b'hello \ r \ r \ nworld!'
It looks like two lines have been broken as above. (It's annoying that it looks like a line break when opened with Windows Notepad …)
\r\n , but because \
\r\n by automatic conversion, it becomes
\r\r\n when opened in binary mode.
When outputting data in text mode (when the second argument of open is not'b'), use
\n instead of