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