正在讀取CSV文件。如果以下列表中沒有任何標題,我想提出錯誤消息。它必須在csv文件中至少有一個標題。 插頭是 age sex city
。我想這樣。謝謝如果未找到標題,會引發錯誤(csv文件)
with open('data.csv') as f:
cf = csv.DictReader(f, fieldnames=['city'])
for row in cf:
print row['city']
正在讀取CSV文件。如果以下列表中沒有任何標題,我想提出錯誤消息。它必須在csv文件中至少有一個標題。 插頭是 age sex city
。我想這樣。謝謝如果未找到標題,會引發錯誤(csv文件)
with open('data.csv') as f:
cf = csv.DictReader(f, fieldnames=['city'])
for row in cf:
print row['city']
這個怎麼樣?
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]
在我對這個問題的理解中,如果找到任何頭文件,需要通過頭文件檢查。否則,它應該引發異常。
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
您需要在'with'語句後縮進。 – beardc