[英]Writing csv file in python3
我目前正在處理這個任務,我必須基本上轉換這個輸入 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。
dict1
開始為空,並且只有在該空 dict 中已經找到 year_month 值時才添加它,顯然它永遠不會。
我不太確定這里的邏輯應該是什么,但是當找不到 year_month 時,您可能需要某種方法來設置默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.