LoginSignup
0
2

More than 3 years have passed since last update.

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

Posted at

test.txtというテキストファイルの中身が、
AAA
BBB
CCC
DDD
である場合に

s = """\
AAA
BBB
DDD
DDD
"""
with open ('test.txt', 'r+') as f:
    print(f.read())
    f.seek(0)
    f.write(s)
実行結果
AAA
BBB
CCC
DDD

でtest.txtというテキストファイルの中身は、
AAA
BBB
DDD
DDD
になる。

r+は読み込み+書き込み。
なので、
もしも、test.txtがないと、
読み込みができず、
エラーとなる。

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