3

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

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

2 回答 2

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]
于 2012-05-27T18:58:57.010 回答
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
于 2012-07-04T22:24:06.873 回答