在python3中编写CSV文件

时间:2018-11-03 21:27:43

标签: python python-3.x csv writing

我目前正在处理此作业,我必须将其转换为 input csv file

变成这个 written csv file

这是我的代码,当前正在我的文件夹中创建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)

2 个答案:

答案 0 :(得分:2)

测试

if year_month in dict1:

“保护” dict1在读取文件时不会被更新。因此,当您写入文件时,您不会获得任何数据。

我想你想让其他部分缩进去

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。

答案 1 :(得分:0)

dict1开始为空,并且只有在该空字典中已经找到year_month值的情况下,您才添加到该值中,显然不会。

我不太确定应该在这里讲什么逻辑,但是大概在找不到year_month时,您可能需要某种方式来设置默认值。

相关问题