python - What is os.linesep for? -
python's os module contains value platform specific line separating string, docs explicitly not use when writing file:
do not use os.linesep line terminator when writing files opened in text mode (the default); use single '\n' instead, on platforms.
previous questions have explored why shouldn't use in context, context useful for? when should use line separator, , what?
the docs explicitly not use when writing file
this not exact, doc says not used in text mode.
the os.linesep
used when want iterate through lines of text file. internal scanner recognise os.linesep
, replace single "\n".
for illustration, write binary file contains 3 lines separated "\r\n" (windows delimiter):
import io filename = "text.txt" content = b'line1\r\nline2\r\nline3' io.open(filename, mode="wb") fd: fd.write(content)
the content of binary file is:
with io.open(filename, mode="rb") fd: line in fd: print(repr(line))
nb: used "rb" mode read file binary file.
i get:
b'line1\r\n' b'line2\r\n' b'line3'
if read content of file using text mode, this:
with io.open(filename, mode="r", encoding="ascii") fd: line in fd: print(repr(line))
i get:
'line1\n' 'line2\n' 'line3'
the delimiter replaced "\n".
the os.linesep
used in write mode: "\n" character converted system default line separator: "\r\n" on windows, "\n" on posix, etc.
with io.open
function can force line separator whatever want.
example: how write windows text file:
with io.open(filename, mode="w", encoding="ascii", newline="\r\n") fd: fd.write("one\ntwo\nthree\n")
if read file in text mode this:
with io.open(filename, mode="rb") fd: content = fd.read() print(repr(content))
you get:
b'one\r\ntwo\r\nthree\r\n'
Comments
Post a Comment