我使用以下代码填充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']])
print(x)打印以下内容
[{'fortysixplus':8,'surprise':11,'female':3,'twentysix':6,
'男':2,'user_id':1,'less15':4,'十六':5,'thirtysix':7,
'中立':10,'快乐':9}] {'fortysixplus':8,'惊喜':11,
'female':3,'twentysix':6,'male':2,'user_id':1,'less15':4,
'十六':5,'thirtysix':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
答案 0 :(得分:1)
这里是使用您的示例数据和Python 3的sa notifyDataSetChanged();
示例。请注意,打开文件以与DictWriter
模块一起使用的正确方法是使用csv
参数。打开newline=''
时,fieldnames
是必需参数,因此类实例知道您想要的列名和顺序。
DictWriter
是一个词典列表。 x
会将每个字典一次性写入输出文件中的一行。您也可以使用writerows
一次写一行。
for row in x: w.writerow(row)