0

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
nicomp
  • 4,344
  • 4
  • 27
  • 60
  • 1
    maybe https://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return-on-windows ? – python_user Mar 19 '21 at 01:13
  • just change this line `with open(csv_file, 'w') as csvfile` like this `with open(csv_file, 'w', newline='') as csvfile` – deadshot Mar 19 '21 at 01:22
  • Does this answer your question? [CSV in Python adding an extra carriage return, on Windows](https://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return-on-windows) – Nick Mar 19 '21 at 01:25

0 Answers0