1

変数 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 動的実行クワイアから着想を得ました。

4

3 に答える 3

3

edit : あなたのコードから判断すると、あなたの関数は s の内容に関連するものを書いているようには見えませんdictwrite_string[0:len(write_string)-1]取得した辞書ごとにファイルに書き込んでいます(これは、write_string最後の末尾のコンマのないコピーにwrite_stringすぎません) key_list

あなたの仕事に適したcsvという名前のクラスを持つpython モジュール があります。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)
于 2013-04-23T16:48:48.913 に答える
0

質問を理解しているかどうかはわかりませんが、理解している場合は、次のものを使用する必要があります: http://docs.python.org/2/library/pickle.html

基本的に、Python オブジェクトをファイルに保存できます。ここにあなたが見なければならない簡単な例があります: http://wiki.python.org/moin/UsingPickle

于 2013-04-23T16:47:59.703 に答える
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])
于 2013-04-23T16:58:03.797 に答える