【问题标题】:Writing csv file in python3在python3中编写csv文件
【发布时间】:2019-04-07 16:58:24
【问题描述】:

我目前正在处理这个任务,我必须基本上转换这个 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)

【问题讨论】:

  • 我们无法使用这些图像测试您的代码。
  • @DManokhin 感谢您提到这个出色的问答 :) 但这不是问题。 OP 显然使用的是 python 3 并使用了正确的 newline="" 语句。
  • 顺便说一句,您不需要 close() 语句,因为您正在为文件使用上下文。

标签: python python-3.x csv writing


【解决方案1】:

测试

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()

then 在循环中,只是一个测试,确保数据是一个数字 then:

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。

【讨论】:

  • 哇现在真的可以用了,谢谢!我还没学过收藏。严格来说是我可以使用计数器还是有其他东西?
  • collections.defaultdict(int) 在该上下文中的工作方式相同。而且它比测试密钥是否在那里更快。
  • 如果我要计算 12 行的第 4 列的平均值,我该怎么做?
【解决方案2】:

dict1 开始为空,并且只有在该空字典中已经找到 year_month 值时才添加它,显然它永远不会。

我不太确定这里的逻辑应该是什么,但是当没有找到 year_month 时,您可能需要一些方法来设置默认值。

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 2011-06-27
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多