Question: Question:
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?
Answer: Answer:
Python automatically converts \n
to OS-specific line breaks, so using os.linesep
on Windows may result in extra line breaks.
Sample code:
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())
Output result:
hello hello
world!
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 …)
os.linesep
outputs \r\n
, but because \ \n
becomes \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 os.linesep
.