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
写入文件我做错了什么?
解决方案
您正在重新初始化循环中的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:你的代码很丑。尝试删除不必要的部分/变量并命名变量更有意义。
推荐阅读
- javascript - Fabric JS 将 Textbox 对象文本限制为仅包含一行文本
- rust - 从未装箱的切片创建 NDArray 的无复制方式?
- asp.net - Asp.Net Identity TwoFactorRememberBrowser Cookie 覆盖第二个用户登录
- formal-verification - 如果属性不满足,UPPAAL 不会显示跟踪
- ios - 为什么 Diffable Datasources 以不同的方式对待类和结构类型?
- leaflet - 将长坐标和纬度坐标划分为子坐标(较小的正方形)?
- r - 合并数据框并按组划分行
- java - 理解Java中的equals方法的麻烦
- spring-batch - Spring Cloud Data Flow UI - 删除平台属性
- r - 使用 broom 和 dplyr 合并数据框中的所有观测值的估计模型后进行预测