尝试将字典写入CSV文件时,Str属性没有键

Joi*_*ois 3 python csv dictionary

我正在尝试使用以下代码将字典写入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
Run Code Online (Sandbox Code Playgroud)

以下是抛出的错误:

AttributeError Traceback(最近一次通话最后一次)在()8 9中表示城市,city_info.items()中的文件名:---> 10 condense_data(filenames ['in_file'],filenames ['out_file'],city)11 print_first_point( filenames ['out_file'])

在condense_data(输入文件,输出文件,城市)中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)156157 def writerows(self,rowdicts):-> 158 return self.writer.writerows(map(self._dict_to_list,rowdicts) )159160#保护Sniffer的类型检查是否排除了complex()

_dict_to_list(self,rowdict)中的/opt/conda/lib/python3.6/csv.py 146 def _dict_to_list(self,rowdict):147如果self.extrasaction ==“ raise”:-> 148rong_fields = rowdict.keys ()-self.fieldnames 149,如果错了_150:引发ValueError(“ dict包含不在字段名中的字段:”

AttributeError:'str'对象没有属性'keys'

我确实在Stack Overflow上看到了这类问题,但没有一个有帮助。

Joh*_*nck 5

您正在使用writerows()应使用的位置writerow(),因为您试图写一行而不是它们的列表。