2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonのDictReaderは列数が違っても読める? 欠けた列と空欄をCSV取り込みで区別する

2
Posted at

CSVを取り込むコードで「DictReader が辞書を返したら、その行を登録する」と書くと、列が足りない行も登録処理まで進みます。Pythonの csv.DictReader は、足りない列を既定で None にし、余った値を既定で None キーのリストに入れます。セルが存在して中身が空なら、値は空文字 '' です。

取り込み時に列数を揃えたいなら、この3つを別々に判定できます。macOS 27.2.1 / Python 3.11.14 で、以下のコードを実行しました。

末尾のカンマ1つで結果が変わる

import csv
from io import StringIO

data = "id,name,note\n1,Aya,\n2,Ren\n3,Mio,ok,extra\n"

for row in csv.DictReader(StringIO(data, newline="")):
    print(row)
{'id': '1', 'name': 'Aya', 'note': ''}
{'id': '2', 'name': 'Ren', 'note': None}
{'id': '3', 'name': 'Mio', 'note': 'ok', None: ['extra']}

1,Aya, には3番目のフィールドがあります。2,Ren ではフィールド自体がありません。3,Mio,ok,extra は note の後ろに余計なフィールドがあります。どの行でも "note" in row は True なので、辞書にキーがあるかだけを調べても列不足は見つけられません。

if not row["note"]: で弾くと、列不足に加えて、空欄を許している正常な行まで落ちます。取り込み形式の検査と、項目ごとの必須チェックを分けると、エラーの理由が伝わります。

ヘッダーと列数を検査する

次は、ヘッダーを id,name,note の順に固定し、列が欠けたレコードと余ったレコードを報告する例です。引用符内のカンマも同じ入力に入れて動かします。

import csv
from io import StringIO

data = 'id,name,note\n1,Aya,\n2,Ren\n3,Mio,ok,extra\n4,Sora,"a,b"\n'
expected = ["id", "name", "note"]
missing = object()
reader = csv.DictReader(StringIO(data, newline=""), restval=missing)

if reader.fieldnames != expected:
    raise ValueError(f"ヘッダーが違います: {reader.fieldnames!r}")

for record_no, row in enumerate(reader, start=1):
    if None in row:
        print(f"レコード{record_no}: 余分な列 {row[None]!r}")
        continue
    absent = [name for name in expected if row[name] is missing]
    if absent:
        print(f"レコード{record_no}: 足りない列 {', '.join(absent)}")
        continue
    print(f"レコード{record_no}: 受付 note={row['note']!r}")
レコード1: 受付 note=''
レコード2: 足りない列 note
レコード3: 余分な列 ['extra']
レコード4: 受付 note='a,b'

不足は専用の目印 missing と is で判定します。ヘッダーを完全一致で検証するので、列名の重複も入口で止まります。

番号はヘッダーを除くレコードの通し番号です。引用符内の改行を含むCSVでは物理行番号とずれます。実測対象はメモリ上の文字列で、Excel出力や別の文字コードは試していません。

必須項目や数値形式は別に検査します。AIが生成した取り込みコードをレビューするときは、空欄・列不足・余分な列をそれぞれテストします。

Python 3.11公式ドキュメントのDictReader


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?