[英]writing json data to csv file using python/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"]});
輸出:(每次寫入后帶有空白行)
您可以在使用大熊貓后解決問題:
import pandas as pd # import pandas
data = pd.read_csv('test_output.csv') # pull in csv file
data = data.iloc[::2] # chop every 2nd row from frame
data.to_csv('test_output.csv',index=False) # save over csv
您應該能夠只將上面的代碼段添加到現有代碼的末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.