Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python - What is os.linesep for?

Python's os module contains a value for a platform specific line separating string, but the docs explicitly say not to use it when writing to a file:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single ' ' instead, on all platforms.

Docs

Previous questions have explored why you shouldn't use it in this context, but then what context is it useful for? When should you use the line separator, and for what?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the docs explicitly say not to use it when writing to a file

This is not exact, the doc says not to used it in text mode.

The os.linesep is used when you want to iterate through the lines of a text file. The internal scanner recognise the os.linesep and replace it by a single " ".

For illustration, we write a binary file which contains 3 lines separated by " " (Windows delimiter):

import io

filename = "text.txt"

content = b'line1
line2
line3'
with io.open(filename, mode="wb") as fd:
    fd.write(content)

The content of the binary file is:

with io.open(filename, mode="rb") as fd:
    for line in fd:
        print(repr(line))

NB: I used the "rb" mode to read the file as a binary file.

I get:

b'line1
'
b'line2
'
b'line3'

If I read the content of the file using the text mode, like this:

with io.open(filename, mode="r", encoding="ascii") as fd:
    for line in fd:
        print(repr(line))

I get:

'line1
'
'line2
'
'line3'

The delimiter is replaced by " ".

The os.linesep is also used in write mode: any " " character is converted to the system default line separator: " " on Windows, " " on POSIX, etc.

With the io.open function you can force the line separator to whatever you want.

Example: how to write a Windows text file:

with io.open(filename, mode="w", encoding="ascii", newline="
") as fd:
    fd.write("one
two
three
")

If you read this file in text mode like this:

with io.open(filename, mode="rb") as fd:
    content = fd.read()
    print(repr(content))

You get:

b'one
two
three
'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...