首页 > 解决方案 > 为什么我的 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

写入文件我做错了什么?

标签: pythoncsv

解决方案


您正在重新初始化循环中的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:你的代码很丑。尝试删除不必要的部分/变量并命名变量更有意义。


推荐阅读