首页 > 解决方案 > 在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)

标签: pythonpython-3.xcsvwriting

解决方案


考试

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。


推荐阅读