0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ファイルを書き込んで読み込む

Posted at
1
s = """\
AAA
BBB
CCC
DDD
"""
with open ('test.txt', 'w') as f:
    f.write(s)

with open ('test.txt', 'r') as f:
    print(f.read())
1の実行結果
AAA
BBB
CCC
DDD

これを

2
s = """\
AAA
BBB
CCC
DDD
"""
with open ('test.txt', 'w+') as f:
    f.write(s)
    f.seek(0)
    print(f.read())

と書ける。
書き込んだ後はインデックスが最後になるので、

f.seek(0)

で先頭に戻る必要がある。

w+は、
書き込み+読み込み。

with open ('test.txt', 'w+') as f:
    print(f.read())

とすると、
まず書き込みモードになり、
一旦、空になり、
何も書き込まず、
読み込む事になるので、
何も出力されない。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?