python - 在python3中编写csv文件
问题描述
我目前正在处理这个任务,我必须基本上转换这个 输入 csv 文件
进入这个 书面的 csv 文件
这是我的代码,目前正在我的文件夹中创建 csv 文件,但实际上并没有在其中写入任何内容。
import csv
def read_calculate():
dict1 = {}
with open('sunspots.csv','r') as file:
csv_reader = csv.reader(file, delimiter=',')
for row in csv_reader:
year_month = row[0] + row[1]
if year_month in dict1:
if(row[4].isnumeric() and int(row[4])!= -1):
dict1[year_month]+= int(row[4])
else:
if(row[4].isnumeric() and int(row[4])!=-1):
dict1[year_month]=int(row[4])
else:
dict1[year_month]=0
file.close()
return dict1
def write_to_file(dict1):
with open('Monthtotal.csv','w',newline='') as write_file:
writer = csv.writer(write_file)
for key in dict1.keys():
line = key[0:4],k[4:6],str(dict1[key])
writer.writerow(line)
write_file.close()
if __name__=='__main__':
dict1 = read_calculate()
write_to_file(dict1)
解决方案
考试
if year_month in dict1:
“保护”dict1
在读取文件时不被更新。因此,当您编写文件时,您不会得到任何数据。
我想你想去缩进 else 部分:
if year_month in dict1:
if(row[4].isnumeric() and int(row[4])!= -1):
dict1[year_month]+= int(row[4])
else:
if(row[4].isnumeric() and int(row[4])!=-1):
dict1[year_month]=int(row[4])
else:
dict1[year_month]=0
但有更聪明的方法,如collections.Counter
:
import collections
dict1 = collections.Counter()
然后在循环中,只是一个测试以确保数据是一个数字然后:
if(row[4].isnumeric() and int(row[4])!= -1):
dict1[year_month] += int(row[4])
else:
dict1[year_month] += 0 # add nothing, but "creates" the key if doesn't exist
你需要这个else
部分(看起来很笨拙,是的,我知道)所以你创建所有月份键,甚至是空的,否则你的 csv 文件会有漏洞。另一种方法是在编写字典时不要循环键(直到 python 3.6 才排序字典),而是在硬编码的月份值上循环。Counter
将在不存在的密钥上产生 0。
推荐阅读
- python - Gitlab 的 Graphql 端点是什么?
- c++ - 在c ++中围绕中心元素构造镜像向量
- php - PHP:将全局变量传递给函数?
- python - 如何根据列标签获取数据框的设置差异?
- elasticsearch - 弹性搜索。根据上一个结果进行搜索的无痛脚本
- javascript - 在初始页面加载时在 Next.js 中获取整个应用程序的全局数据
- r - R从矩阵中得到回归线
- string - 将 unicode 转换为“java”
- python - 如何通过gspread清除谷歌表格中的范围
- charts - Allow users turn colour breakdown / legend on and off on a bar chart