使用python / pymongo将json数据写入csv文件

时间:2017-10-10 23:00:38

标签: python mongodb pymongo

我从mongodb&获取数据使用csv.DictWriter方法将json值写入csv文件,但在写入时我在每行之后得到一个空行。

如何避免这些空白行?

代码片段:(我正在做一些我没有在这里包含的数据操作)

with open('test_output.csv', 'w') as csvfile:
  fields = ['date', 'ns', 'storageSize']
  writer = csv.DictWriter(csvfile, fieldnames=fields)
  writer.writeheader()
  stats = client['db_stats'].coll_stats.find({})
  for x in stats:
     writer.writerow({'date': x["date"], 'ns': x["ns"], 'storageSize': x["storageSize"]});

输出:(每次写入后留空行)

enter image description here

1 个答案:

答案 0 :(得分:0)

你可以用pandas解决问题:

main_area_text = #this is equal to the html text above
                 #I've verified this with a watch during debugging
                 #But this doesn't actually matter, because you can put
                 #anything in here and it still doesn't work
html_file_path = os.getcwd() + "\\data\\myfile.html"
if os.path.isfile(html_file_path):
    print("File exists!")
    actual_file = open(html_file_path, "a")
    actual_file.write(main_area_text)
else:
    print("File does not exist!")
    actual_file = open(html_file_path, "w")
    actual_file.write(main_area_text)

您应该只需将上面的代码段添加到现有代码的末尾即可。