HOWTO · Python
Python AttributeError: _csv.reader オブジェクトに次の属性がありません
このチュートリアルでは、Python で AttributeError: _csv.reader object has no attribute next を修正する方法を説明します。
このページの内容
CSV 形式は、スプレッドシートやデータベースで最もよく使用される形式の 1つです。 Python 言語には、CSV 形式でデータを読み書きするためのクラスを提供する csv モジュールがあります。
属性は、オブジェクトまたはクラスに関連する値です。 メソッドでサポートされていないタイプのオブジェクトの属性を呼び出すと、Python で AttributeError が発生します。
たとえば、ファイル オブジェクトで split() メソッドを使用すると、AttributeError が返されます。これは、ファイル オブジェクトが split() メソッドをサポートしていないためです。
このチュートリアルでは、Python で AttributeError: '_csv.reader' object has no attribute 'next' を修正する方法を説明します。
Python の AttributeError: '_csv.reader' object has no attribute 'next' エラーを修正
csv.reader オブジェクトは反復子です。 next() メソッドは csv.reader オブジェクトで使用でき、反復可能なオブジェクトの次の行を返します。
import csv
with open(csvfile) as f:
reader = csv.reader(f, delimiter=",", quotechar='"', skipinitialspace=True)
header = reader.next()
f.close()
出力:
line 5, in <module>
header = reader.next()
AttributeError: '_csv.reader' object has no attribute 'next'
しかし Python 3 では、reader.next() メソッドの代わりに組み込み関数 next(reader) を使用する必要があります。
import csv
with open(csvfile) as f:
reader = csv.reader(f, delimiter=",", quotechar='"', skipinitialspace=True)
header = next(reader)
f.close()
これで、Python で AttributeError が解決されるはずです。 この記事がお役に立てば幸いです。