代码之家  ›  专栏  ›  技术社区  ›  user6092898

数据未写入csv

  •  0
  • user6092898  · 技术社区  · 7 年前

    Im使用以下代码填充csv

    f = csv.writer(open("test.csv", "w"))
    
    f.writerow(["user_id", "male", "female", "less15", "sixteen", "twentysix", 
                "thirtysix", "fortysixplus", "happy","neutral", "surprise"])
    
    
    if __name__ == '__main__':
    
        with tf.Session() as sess:
            start_time = timeit.default_timer()
    
            x = json.loads(createjson(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))
            print(x)
    
            for row in x:
                print(row)
                f.writerow([row['user_id'], row['male'], row['female'], row['less15'], 
                            row['sixteen'], row['twentysix'], row['thirtysix'], 
                            row['fortysixplus'], row['happy'], row['neutral'], row['surprise']])
    

    打印(x)打印以下内容


    “男”:2,“用户id”:1,“less15”:4,“十六”:5,“三十六”:7,
    “中立”:10,“快乐”:9}]{fortysixplus:8,“惊喜”:11,
    “女性”:3,“二十六”:6,“男性”:2,“用户id”:1,“less15”:4,
    “十六”:5,“三十六”:7,“中立”:10,“快乐”:9}

    但是,数据不是以csv格式写入的。为什么会这样?

    我试着使用dictwriter,如下所示,

    if __name__ == '__main__':
        with tf.Session() as sess:
    
            start_time = timeit.default_timer()
            x = json.loads(createjson(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))
    
    
            for row in x:
                print(row)
                writer = csv.DictWriter(f = open('test.csv', 'w'), fieldnames=row.keys)
                # writer.writeheader()
                writer.writerow(row)
    

    但我仍然得到以下错误,

    Traceback (most recent call last):
      File "C:/Users/R&D/Documents/Maxis_2/Maxis/src/dwell_time_maxis.py", line 128, in <module>
        writer.writerow(row)
      File "C:\Program Files\Anaconda3\lib\csv.py", line 153, in writerow
        return self.writer.writerow(self._dict_to_list(rowdict))
      File "C:\Program Files\Anaconda3\lib\csv.py", line 146, in _dict_to_list
        wrong_fields = [k for k in rowdict if k not in self.fieldnames]
      File "C:\Program Files\Anaconda3\lib\csv.py", line 146, in <listcomp>
        wrong_fields = [k for k in rowdict if k not in self.fieldnames]
    TypeError: argument of type 'builtin_function_or_method' is not iterable
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Mark Tolonen    7 年前

    这是一个 DictWriter csv 模块将使用 newline='' 参数 fieldnames 是打开时必需的参数 因此,类实例知道您需要什么列名以及列名的顺序。

    x writerows for row in x: w.writerow(row) 一次写一行。

    x = [{'fortysixplus': 8, 'surprise': 11, 'female': 3, 'twentysix': 6,
          'male': 2, 'user_id': 1, 'less15': 4, 'sixteen': 5, 'thirtysix': 7,
          'neutral': 10, 'happy': 9}]
    
    with open('test.csv','w',newline='') as f:
        w = csv.DictWriter(f,fieldnames='user_id male female less15 sixteen twentysix thirtysix fortysixplus happy neutral surprise'.split())
        w.writeheader()
        w.writerows(x)