LoginSignup
2
2

More than 5 years have passed since last update.

with構文とfor文を使ったスマートなファイル操作

Posted at

Python3.6を使っています。

file_copy.py
with open("src.txt", "r") as sf, open("dst.txt", "w") as df:
    # 一行ずつ読み込む
    for line in sf:
        df.write(line)

with構文のところは下記のように書き換え可能。

with open("src.txt", "r") as sf:
    with open("dst.txt", "w") as df:
    # 以下、省略

with構文を使うことにより、try...finallyで最後にclose()する必要がなくなる。

2
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
2
2