开发者

python csv header error

开发者 https://www.devze.com 2022-12-21 16:58 出处:网络
Trying to read headers for a csv file with: reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)

Trying to read headers for a csv file with:

reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames

for header in sorted(set(开发者_C百科headers)):

It worked on development server, throws this error on production

'NoneType' object is not iterable

Debug shows headers has None value while the csv file has headers in it.

headers:None


From csvreader.fieldnames documentation:

If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.

So try reading the first row from the file, then reader.fieldnames should contain the data you need. Maybe something like adding reader.next():

reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
reader.next()
headers = reader.fieldnames

The documentation also says:

Changed in version 2.6.

So this difference in behaviour could be due to a difference in Python version between your two systems.


Maybe you're using different Python versions in your development server vs production? In Python 2.5, the fieldnames attribute of a DictReader instance is None until the instance has been used to fetch at least one row.

0

精彩评论

暂无评论...
验证码 换一张
取 消