ドキュメントは、ファイルへの書き込み時にそれを使用しないように明示的に言っています
これは正確ではありません。ドキュメントでは、テキストモードでは使用しないように指示されています。
はos.linesep
、テキスト ファイルの行を反復処理する場合に使用されます。内部スキャナは を認識os.linesep
し、単一の「\n」に置き換えます。
説明のために、"\r\n" (Windows 区切り文字) で区切られた 3 行を含むバイナリ ファイルを作成します。
import io
filename = "text.txt"
content = b'line1\r\nline2\r\nline3'
with io.open(filename, mode="wb") as fd:
fd.write(content)
バイナリ ファイルの内容は次のとおりです。
with io.open(filename, mode="rb") as fd:
for line in fd:
print(repr(line))
注意: 「rb」モードを使用して、ファイルをバイナリ ファイルとして読み取りました。
私は得る:
b'line1\r\n'
b'line2\r\n'
b'line3'
次のように、テキスト モードを使用してファイルの内容を読み取る場合:
with io.open(filename, mode="r", encoding="ascii") as fd:
for line in fd:
print(repr(line))
私は得る:
'line1\n'
'line2\n'
'line3'
区切り文字は「\n」に置き換えられます。
はos.linesep
書き込みモードでも使用されます。「\n」文字は、システムのデフォルトの行区切り文字に変換されます。Windows では「\r\n」、POSIX では「\n」などです。
関数を使用io.open
すると、行区切りを任意のものに強制できます。
例: Windows テキスト ファイルの書き方:
with io.open(filename, mode="w", encoding="ascii", newline="\r\n") as fd:
fd.write("one\ntwo\nthree\n")
このファイルをテキストモードで次のように読むと:
with io.open(filename, mode="rb") as fd:
content = fd.read()
print(repr(content))
あなたは得る:
b'one\r\ntwo\r\nthree\r\n'