我有一个存储在变量List_dicts中的字典项列表,我必须将上面列表中选定的项目列表写入文件。在我的python函数下面给出:
def write_items(List_dicts,key_list):
#List_dicts contains the list if dicts
#key_list contains the key separated by comma
k_list=key_list.split(',')
write_string=''
for i in k_list:
write_string=write_string+"item['"+i+"'],"
f=open('log.txt','w')
for item in List_dicts:
f.write(write_string[0:len(write_string)-1]) #this should write item['key1'],item['key2'],item['key3']..,item['keyn'] not the value of string 'write_string'
f.close()
这有可能吗?我受到了SQL动态执行quires的启发。
答案 0 :(得分:3)
编辑:根据您的代码判断,您的函数似乎没有编写与dict
s内容相关的任何内容。你正在为你的每个dict写一个write_string[0:len(write_string)-1]
(这只是你的write_string
没有最后一个逗号的副本)而且write_string
对你的dict中的项目没有任何意义,它只是key_list
中选定的键。
有一个python模块csv
,有一个名为DictWriter
的类,适合你的工作。
import csv
def write_dicts(dicts, keys, filename):
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, keys, extrasaction='ignore')
for d in dicts:
writer.writerow(d)
答案 1 :(得分:0)
我不确定我是否理解这个问题,但如果我这样做,这就是你应该使用的: http://docs.python.org/2/library/pickle.html
基本上它允许你将python对象存储在文件中。 这是一个你应该看一下的简单示例: http://wiki.python.org/moin/UsingPickle
答案 2 :(得分:0)
除了最好使用csv
模块之外,你做错了的是你过于复杂的事情。
您已经有一个要写入的密钥列表,因此只需直接直接这些密钥:
def write_items(List_dicts, key_list):
k_list = key_list.split(',')
with open('log.txt','w') as f:
for item in List_dicts:
for key in k_list:
f.write(item[key])