我正在尝试使用以下代码将字典写入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(最近一次调用last)in()8 9 for city,filenames in city_info.items():---> 10 condense_data(filenames ['in_file'],filenames ['out_file'],city)11 print_first_point (文件名['out_file'])在condense_data(in_file,out_file,city)中38 ##请参阅https://docs.python.org/3/library/csv.html#writer-objects## 39 print(new_point) - - > 40 trip_writer.writerows(new_point)41 42 /opt/conda/lib/python3.6/csv.py in writerows(self,rowdicts)156 157 def writer((self,rowdicts): - > 158返回self . writer.writerows(map(self._dict_to_list,rowdicts))159 160 #Wore Sniffer的类型检查反对在_dict_to_list(self,rowdict)中排除complex()/opt/conda/lib/python3.6/csv.py的构建版本146 def _dict_to_list(self,rowdict):147如果self.extrasaction ==“raise”: - > 148 wrong_fields = rowdict.keys() - self.fieldnames 149 if wrong_fields:150引发ValueError(“dict包含不在fieldnames中的字段:” AttributeError:'str'对象没有属性'keys'
我确实在Stack Overflow上看到了这类问题,但没有一个有用 .
1 回答
你正在使用
writerows()
,你应该使用writerow()
,因为你试图写一行,而不是它们的列表 .