Why does the the resulting .CSV file have interspersed blank lines?
# https://www.tutorialspoint.com/How-to-save-a-Python-Dictionary-to-CSV-file
import csv
csv_columns = ['No','Name','Country'] # These are dictionary keys, they map to columns in the CSV file
dict_data = [
{'No': 1, 'Name': 'Alex', 'Country': 'India'},
{'No': 2, 'Name': 'Ben', 'Country': 'USA'},
{'No': 3, 'Name': 'Shri Ram', 'Country': 'India'},
{'No': 4, 'Name': 'Smith', 'Country': 'USA'},
{'No': 5, 'Name': 'Yuva Raj', 'Country': 'India'},
]
csv_file = "NamesExample.csv" #relative path
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict_data: # One dictionary at a time
writer.writerow(data)
except IOError:
print("I/O error")
This is what I get when I run the above code:
No,Name,Country
1,Alex,India
2,Ben,USA
3,Shri Ram,India
4,Smith,USA
5,Yuva Raj,India