我有一个很大的csv,文件,我想获得其中的所有值,这些值存储在我知道名称的特定列中。
不知怎的,我不明白该怎么做,但我想我很接近:(
import codecs
import csv
import json
import pprint
import re
FIELDS = ["name", "timeZone_label", "utcOffset", "homepage","governmentType_label", "isPartOf_label", "areaCode", "populationTotal",
"elevation", "maximumElevation", "minimumElevation", "populationDensity", "wgs84_pos#lat", "wgs84_pos#long",
"areaLand", "areaMetro", "areaUrban"]
index=[]
with open('/Users/stephan/Desktop/cities.csv', "r") as f:
mycsv=csv.reader(f)
results=[]
headers=None
for row in mycsv:
for i, col in enumerate(row):
if col in FIELDS:
index.append(i)
print row[i]
print index
我的列表索引,我认为是正确的,并给了我正确的值(列索引)
我需要在代码中添加什么才能使其正常工作?
答案 0 :(得分:2)
import csv
with open('/Users/stephan/Desktop/cities.csv', "r") as f:
mycsv = csv.DictReader(f)
for row in mycsv:
for col in FIELDS:
try:
print(row[col])
except KeyError:
pass
答案 1 :(得分:0)
如果您要打印FIELDS
中这些列中的所有值,您要做的是:
for row in mycsv:
for i, col in enumerate(row):
# If this is the header row entry for one of the columns we want, save its index value
if col in FIELDS:
index.append(i)
# If this is one of the columns in FIELDS, print its value
elif i in index:
print col