好的我正在用Python编写程序。我只想弄清楚为什么它没有写入csv文件吧?它写入它但只输出的最后一行。我甚至尝试写一个文本文件,但结果相同。我需要帮助理解为什么它不打印所有输出。
这就是我所做的。
import csv
#import copy
def main():
Moderate = []
Strong= []
Major=[]
Great=[]
Overall=[]
Region=[]
infile=open("earthquakes.txt", "r")
infile.readline()
for line in infile:
line=line.strip().split('\t')
if line[6] not in Region:
Region.append(line[6])
if float(line[1]) >=8:
Great.append(1)
else:
Great.append(0)
if float(line[1])>=7 and float(line[1])<=7.9:
Strong.append(1)
else:
Strong.append(0)
if float(line[1])>=6 and float(line[1])<=6.9:
Major.append(1)
else:
Major.append(0)
if float(line[1])>=5 and float(line[1])<=5.9:
Moderate.append(1)
else:
Moderate.append(0)
#print(len(Region),len(Moderate),len(Great),len(Major),len(Strong))
else:
i=Region.index(line[6])
if float(line[1]) >=8:
Great[i]+=1
if float(line[1])>=7 and float(line[1])<=7.9:
Strong[i]+=1
if float(line[1])>=6 and float(line[1])<=6.9:
Major[i]+=1
if float(line[1])>=5 and float(line[1])<=5.9:
Moderate[i]+=1
for i in range(len(Region)):
str1=str(Region[i])+","
str1+=str(Moderate[i])+","
str1+=str(Major[i])+","
str1+=str(Great[i])+","
str1+=str(Strong[i])+","
Overall=Moderate[i]+Major[i]+Great[i]+Strong[i]
str1+=str(Overall)
#print(Overall)
print(str1)
cvsFile=open("earthquake.cvs",'w')
# for i in range(len(Region)):
words=['Region,Great,Major,Strong,Moderate,Overall']
w=csv.writer(cvsFile,delimiter=' ')
w.writerows(words)
cvsFile.write(str1)
if __name__ == "__main__":
main()
答案 0 :(得分:0)
我觉得你需要更多地研究这段代码,但试试这个:
with open('earthquake.csv', 'a') as csvFile:
for i in range(len(Region)):
str1 = ','.join([Region[i], Moderate[i], Major[i], Great[i], Strong[i], ''])
Overall = ''.join[Moderate[i], Major[i], Great[i], Strong[i]]
str1 += Overall
# print(Overall)
# print(str1)
words = ['Region,Great,Major,Strong,Moderate,Overall']
w = csv.writer(csvFile, delimiter=' ')
w.writerows(words)
csvFile.write(str1)