0

I'm getting the data from mongodb & using csv.DictWriter method to write the json values to the csv file, but while writing I'm getting a blank line after each row.

How to avoid these blank lines?

Code Snippet: (I'm doing some data manipulation which i didn't include here)

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"]});

Output:(with blank lines after each write)

enter image description here

Siva Dasari
  • 1,059
  • 2
  • 19
  • 40
  • 1
    Possible duplicate of [CSV file written with Python has blank lines between each row](https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row) – foxyblue Oct 10 '17 at 23:03

1 Answers1

0

You can fix the problem after the fact with pandas:

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

You should be able to just add the snippet above to the end of your existing code.

Jeff Saltfist
  • 933
  • 3
  • 15
  • 30