0
1

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 1 year has passed since last update.

タイトル付きCSVを一行づつJSONで取り出す。

Last updated at Posted at 2021-12-14

ちょ、予告なしに列順変えてくるんじゃねぇよ!

なんか突然ある日項目が増えて列の参照が狂うみたいな、そんな困ったCSVを送ってくるクライアントをお持ちのあなた! そうあなた!
これを使えばもう安心です(おおよそな

ただしタイトル行があるのが前提。
無かったら・・・(目を反らす

ていうか今どきCSVとかつk(

コード

import csv

class CSVobj:

    def __init__(self, filename):
        self.filename = filename

    def read(self, enc="utf-8"):
        with open(self.filename, "r", encoding=enc) as fr:
            reader = csv.reader(fr)
            for idx, row in enumerate(reader):
                if len(row) > 0:

                    # 最初の行はタイトル
                    if idx == 0:
                        titles = row

                    # {タイトル:データ}でdictにしてyield
                    else:
                        buf = {}
                        for tidx, title in enumerate(titles):
                            buf[title] = row[tidx]

                        yield buf

    def __enter__(self):
        return self

    def __exit__(self, enctype, excvalue, traceback):
        pass

if __name__ == "__main__":
    with CSVobj("imadoki.csv") as cobj:
        for row in cobj.read():
            print(">>" , row)

使い方

JSONというかdict型で一行づつ取り出します。

mainのところを見てもらえばそのままです。
これで数万行あるわけのわからないCSVを毎回毎回送ってこられた上に列順が変わっても対処可能!

さあ、負けるな!

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?