如果没有找到标头,则引发错误(csv文件)

时间:2012-05-27 18:55:47

标签: python

阅读CSV文件。如果以下列表中没有任何标头,我想提出错误消息。它必须至少是csv文件中的一个标头。 标题是 age sex city。我是这样想的。感谢

with open('data.csv') as f:
  cf = csv.DictReader(f, fieldnames=['city'])
  for row in cf:
    print row['city']

2 个答案:

答案 0 :(得分:1)

这个怎么样?

import csv

with open('data.csv', 'rb') as inf:
    cf = csv.reader(inf)

    header = cf.next()
    if header != ['Age', 'Sex', 'City']:
        print "No header found"
    else:
        for row in cf:
            print row[2]

答案 1 :(得分:0)

在我对该问题的理解中,如果找到任何标题,则需要传递标题检查。否则它应该引发异常。

import csv

with open('data.csv','rb') as f:
    fieldnames = ['age','sex','city']
    cf = csv.DictReader(f)
    headers = cf.fieldnames

    if len(set(fieldnames).intersection(set(headers))) == 0:
        raise csv.Error("CSV Error: Invalid headers: %s" % str(headers))

    for row in cf:
        city = row['city'] if 'city' in headers else "N/A"
        sex = row['sex'] if 'sex' in headers else "N/A"
        age = row['age'] if 'age' in headers else "N/A"
        print "city: " + city + ", sex: " + sex + ", age: " + age