LoginSignup
24
17

More than 3 years have passed since last update.

【Python】2つ以上の複数ファイルを同時にopenする方法

Posted at

Pythonで2つ以上の複数ファイルを同時にopenしたい場合があると思います。
例えば、あるファイルを読み込んで何かしらの処理をし、結果を別のファイルに書き込むというような場合です。

素直にプログラムを書くと、

with open('./output.txt', mode='w') as fw:
    with open('./input.txt', mode='r') as fi:
        for line in fi:
            i = int(line.strip())
            i += 1 # 1を足すだけの処理
            fw.write(str(i) + '\n')

となると思います。

input.txt

1
2
3

だとすると、output.txt

2
3
4

となります。

ただ、前記のプログラムはwith句が入れ子になっており、インデントが深くなりスマートではありません。
実はこのプログラム、次のようにwith句を一つにまとめて書くことができます。

with open('./input.txt', mode='r') as fi, open('./output.txt', mode='w') as fw:
    for line in fi:
        i = int(line.strip())
        i += 1 # 1を足すだけの処理
        fw.write(str(i) + '\n')

インデントも浅くなり少し(?)スマートになったと思います。

24
17
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
24
17