2
5

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.

Pythonのwith文で複数ファイルを一度に開く

Last updated at Posted at 2021-01-21

概要

Pythonでファイルのopenなどに使うwith文は、カンマで区切って複数のファイルを一度に開くことができます。(python3.1以降)
その場合、複数の with 文がネストされたかのように扱われます。
複数csvファイルのマージなどに役立ちます。

サンプルコード(python3.6.9で確認)

2021-01-22: @shiracamus さんのコメントを反映しました。ありがとうございます。

import csv

with open("input1.csv", mode='r') as fi1, \
     open("input2.csv", mode='r') as fi2, \
     open("output.csv", mode='w') as fo:
    reader1 = csv.reader(fi1)
    reader2 = csv.reader(fi2)
    writer = csv.writer(fo)

    for l1, l2 in zip(reader1, reader2):
        writer.writerow(l1 + l2)

入力ファイル

input1.csv

a,b,c
1,2,3

input2.csv

d,e,f
4,5,6

出力結果

output.csv

a,b,c,d,e,f
1,2,3,4,5,6

公式ドキュメント

8. 複合文 (compound statement)「8.5. with 文」

2
5
3

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
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?