我正在尝试抓取一些数据,将该数据写入 CSV 文件,然后将该 CSV 文件导入到 R 中以对其进行一些分析。这更多的是一个学习 python 和 R 的个人项目,我在打印到 CSV 文件时遇到了一些问题。我现在以完全困惑的方式打印出来,R 确实无法按照我想要的方式使用数据。有人有什么建议吗?以下是 csv 文件的代码:
with open('cdc_data.csv','w', newline='',) as f:
i = 0
fieldnames = ['Country', 'Infected', 'Deaths']
thewriter = csv.DictWriter(f, fieldnames=fieldnames)
print("Country /", end=' ')
print("Infected /", end=' ')
print("Deaths /", end=' ')
print("Location:", end=' ')
print(" ")
thewriter.writeheader()
for x in infectionData:
while i <= 83:
print(infectionData[i], end=' ')
thewriter.writerow({'Country': infectionData[i]})
i += 1
print(infectionData[i], end=' ')
thewriter.writerow({'Infected': infectionData[i]})
i += 1
print(infectionData[i], end=' ')
thewriter.writerow({'Deaths': infectionData[i]})
i += 1
print(infectionData[i])
# thewriter.writerow({'Location': infectionData[i]})
i += 1
我添加了当前输出的外观,我正在尝试获取它,因此它看起来更像这样 国家/感染者/死亡人数/地点 中国/1771/170/亚洲 等等
这是 print(infectedData) 输出的内容:
['China', '7,711', '170', 'Asia', 'Thailand', '14', '0', 'Asia', 'Hong Kong', '11', '0', 'Asia', 'Taiwan', '8', '0', 'Asia', 'Macau', '7', '0', 'Asia', 'Malaysia', '7', '0', 'Asia', 'Singapore', '10', '0', 'Asia', 'Japan', '8'
继续前进
最佳答案
import csv
def remove_comma(s):
return s.replace(',', '')
def export_to_csv(data,filename='cdc_data.csv'):
with open(filename,'w', newline='',) as f:
fieldnames = ['Country', 'Infected', 'Deaths', 'Location']
thewriter = csv.DictWriter(f, fieldnames=fieldnames)
print(' / '.join(fieldnames))
thewriter.writeheader()
i=0
while i+3<len(data):
x=data[i:i+4]
x[1]=remove_comma(x[1])
x[2]=remove_comma(x[2])
thewriter.writerow({'Country': x[0],'Infected':x[1],'Deaths':x[2],'Location':x[3]})
print(' '.join([str(val) for val in x]))
i+=4
#call it like:
infectionData=['China', '7,711', '170', 'Asia', 'Thailand', '14', '0', 'Asia', 'Hong Kong', '11', '0', 'Asia', 'Taiwan', '8', '0', 'Asia', 'Macau', '7', '0', 'Asia', 'Malaysia', '7', '0', 'Asia', 'Singapore', '10', '0', 'Asia']
export_to_csv(infectionData)
或者,如果默认值不合适,您也可以添加文件名。
关于python - 如何在Python中正确打印CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59977896/