0
0

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.

ファイルの書き込み読み込み

Last updated at Posted at 2020-08-25

ファイルの読み込みと書き込みを同時に行いたい場合

w+を使う場合

"w+"は読み込みと書き込みが可能
sの内容をファイルに書き込み
seekで先頭に戻り、読み込んでいる
ここでseekを用いないとエラーが発生する

qiita.py
s="""\
AAA
BBB
CCC
DDD
"""

with open("test.text", "w+") as f:
    f.write(s)
    f.seek(0)
    print(f.read())

実行結果

AAA
BBB
CCC
DDD

注意点

"w+"で書き込み、読み込みはできるが
実行した時点でファイルの中身が消えてしまう
次のように読み込みのみしようとすると

qiita.py
s="""\
AAA
BBB
CCC
DDD
"""

with open("test.text", "w+") as f:
    # f.write(s)
    # f.seek(0)
    print(f.read())

実行結果


r+を使う場合

wのときとは違い読み込むファイルがないとエラーになるので注意

qiita.py
s="""\
AAA
BBB
CCC
DDD
"""

with open("test.text", "r+") as f:
    print(f.read())
    f.seek(0)
    f.write(s)
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?