我正在获取一个带有标题行(称为aggregate_file
)的 csv 文件,按列对其进行排序,然后将其重新写入另一个 csv 文件(称为sorted_file
)。我要排序的列标题由variable_names
.
def sortbyCounty(aggregate_file, sorted_file, *variable_names):
f = open(aggregate_file, 'r')
readit = csv.reader(f)
headers = readit.next()
col_indices = []
for var in variable_names:
col_indices.append(headers.index(var))
print col_indices
thedata = list(readit)
thedata.sort(key=operator.itemgetter(col_indices))
fx = open(sorted_file, 'w')
writeit = csv.writer(fx)
writeit.writerow(headers)
writeit.writerows(thedata)
writeit.close()
return sorted_file
接下来,我在以下几行中调用此函数:
aggregate_file = "Aggregate_test90.csv"
sorted_file = "County_test90.csv"
variable_names = 'CTYCODE90'
test = sortbyCounty(aggregate_file, sorted_file, *variable_names)
这是我的错误信息:
col_indices.append(headers.index(var))
ValueError: list.index(x): x not in list
但是,当我列出print
我的headers
列表时,我可以清楚地看到我的变量存在:
['_STATE90', 'HEIGHT90', 'WEIGHT90', '_BMI90', 'AGE90', 'CTYCODE90', 'IYEAR90', 'SEX90', '_RFOBESE90']
所以我完全不明白为什么我会收到此错误消息。我错过了什么?