为什么我的csv文件只写一行?

时间:2020-04-03 02:33:41

标签: python csv

import csv
def write_to_dictionaries_to_csv(csvWriter,lst_dic,lst_keys):
  for dic in data:
    lst = []
    for key in lst_keys:
      if key in dic:
        value = dic[key]
        lst.append(value)
    return lst

data = [{'tow_reason': 'IL', 'tow_date': '2013-06-18'}, {'tow_date': '2014-09-25', 'tow_reason': 'GA'}]

with open("smallDataFileIWrote.csv", 'w') as f_out:
  csv_w = csv.writer(f_out)
  result = write_to_dictionaries_to_csv(csv_w, data, ['tow_reason','tow_date'])
  csv_w.writerow(result)

为什么这段代码只写:

IL,2013-06-18

到文件?

我希望文件同时具有:

IL, 2013-06-18
GA, 2014-09-25

写到文件中我在做什么错了?

2 个答案:

答案 0 :(得分:0)

您每次在循环中都要重新初始化lst,然后在循环内返回。

将其删除:

def write_to_dictionaries_to_csv(csvWriter,lst_dic,lst_keys):
    lst = []
    for dic in data:
        row = []
        for key in lst_keys:
            if key in dic:
                value = dic[key]
                row.append(value)
        lst.append(row)
    return lst

写作:

result = write_to_dictionaries_to_csv(csv_w, data, ['tow_reason','tow_date'])
for row in result:
  csv_w.writerow(row)

最终代码:

import csv


def write_to_dictionaries_to_csv(lst_keys):
    lst = []
    for dic in data:
        row = []
        for key in lst_keys:
            if key in dic:
                value = dic[key]
                row.append(value)
        lst.append(row)
    return lst


data = [{'tow_reason': 'IL', 'tow_date': '2013-06-18'},
        {'tow_date': '2014-09-25', 'tow_reason': 'GA'}]

with open('smallDataFileIWrote.csv', 'w', newline='\n', encoding='utf-8') as f_out:
    csv_w = csv.writer(f_out)
    result = write_to_dictionaries_to_csv(['tow_reason', 'tow_date'])
    for row in result:
        csv_w.writerow(row)

P / s:您的代码非常难看。尝试删除不必要的部分/变量,并更有意义地命名变量。

答案 1 :(得分:0)

您的lst为空,因为它在循环内。试试这个

import csv
def write_to_dictionaries_to_csv(csvWriter,lst_dic,lst_keys):
lst = []
for dic in data:

for key in lst_keys:
  if key in dic:
    value = dic[key]
    lst.append(value)
return lst

data = [{'tow_reason': 'IL', 'tow_date': '2013-06-18'}, {'tow_date': '2014-09-25', 'tow_reason': 'GA'}]

with open("smallDataFileIWrote.csv", 'w') as f_out:
 csv_w = csv.writer(f_out)

结果= write_to_dictionaries_to_csv(csv_w,数据,['tow_reason','tow_date']) csv_w.writerow(result)