【发布时间】:2018-05-05 16:23:00
【问题描述】:
我正在尝试使用以下代码将字典写入 CSV 文件:
def condense_data(in_file, out_file, city):
"""
This function takes full data from the specified input file
and writes the condensed data to a specified output file. The city
argument determines how the input file will be parsed.
HINT: See the cell below to see how the arguments are structured!
"""
with open(out_file, 'w') as f_out, open(in_file, 'r') as f_in:
# set up csv DictWriter object - writer requires column names for the
# first row as the "fieldnames" argument
out_colnames = ['duration', 'month', 'hour', 'day_of_week', 'user_type']
trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames)
trip_writer.writeheader()
## TODO: set up csv DictReader object ##
trip_reader = csv.DictReader(f_in)
# collect data from and process each row
for row in trip_reader:
# set up a dictionary to hold the values for the cleaned and trimmed
# data point
new_point = {}
## TODO: use the helper functions to get the cleaned data from ##
## the original data dictionaries. ##
## Note that the keys for the new_point dictionary should match ##
## the column names set in the DictWriter object above. ##
duration = duration_in_mins(row, city)
month, hour, day_of_week = time_of_trip(row, city)
user_type = type_of_user(row, city)
new_point = {'duration': duration, 'month': month, 'hour': hour,
'day_of_week': day_of_week, 'user_type': user_type}
print(new_point) # Works fine till here, I am able print the right output
trip_writer.writerows(new_point) # throws an error
下面是抛出的错误:
AttributeError Traceback(最近调用 最后)在() 8 9 代表城市,city_info.items() 中的文件名: ---> 10 condense_data(文件名['in_file'],文件名['out_file'],城市) 11 print_first_point(文件名['out_file'])
in condense_data(in_file, out_file, 城市) 38 ##见https://docs.python.org/3/library/csv.html#writer-objects## 39 打印(新点) ---> 40 trip_writer.writerows(new_point) 41 42
/opt/conda/lib/python3.6/csv.py in writerows(self, rowdicts) 156 157 def writer(自我,rowdicts): --> 158 返回 self.writer.writerows(map(self._dict_to_list, rowdicts)) 159 160 # Guard Sniffer 对排除 complex() 的构建进行类型检查
/opt/conda/lib/python3.6/csv.py in _dict_to_list(self, rowdict) 146 def_dict_to_list(自我,行字典): 147如果self.extrasaction ==“提高”: --> 148 wrong_fields = rowdict.keys() - self.fieldnames 149 如果错误字段: 150 raise ValueError("dict 包含不在字段名中的字段:"
AttributeError: 'str' 对象没有属性 'keys'
我确实在 Stack Overflow 上看过这类问题,但没有一个有帮助。
【问题讨论】:
标签: python csv dictionary