【发布时间】: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