python - 如何在Python中正确打印CSV文件

标签 python r

我正在尝试抓取一些数据,将该数据写入 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'

继续前进

Image of CSV output

最佳答案

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/

相关文章:

python - 为什么保存到数据库后 CreateView 中的 self.object 没有 id?

python - Python代码中如何处理 "MemoryError"

python - 如何使用Selenium + Python点击链接

r - 为预测/时间序列对象操作 x 轴

r - 用 1 或 0 填充列,如果该列名与在同一数据帧内的其他命名列中找到的变量匹配

python - AWS EKS - 从 pod 内部验证 Kubernetes python lib

python - Convolution2D 可以处理矩形图像吗?

r - 如何在 R 中生成随机的 64 位十六进制数?

r - ggpairs 与颜色分组的总体相关性?

r - R 中的嵌套函数、sys.parent 和环境