2013-04-23 69 views
1

我有一個存儲在變量List_dicts中的字典項目列表,我必須從上面的列表中選擇一個項目列表寫入一個文件。下面給出我的python函數: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

使用CSV與dictwriter – thkang 2013-04-23 16:46:09

回答

3

編輯:從您的代碼來看,你的功能似乎並沒有被寫入相關的dict S中的任何內容。您正在爲每個字典(這是您的write_string沒有最後一個尾隨逗號的副本)寫入write_string[0:len(write_string)-1]到您的文件中,並且write_string與您的字典中的項目沒有任何關係,它只是從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) 
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])