1

I have a below code which is creating a csv file:

import csv

# my data rows as dictionary objects
mydict = [{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
          {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
          {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
          {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
          {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
          {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]

# field names
fields = ['name', 'branch', 'year', 'cgpa']

# name of csv file
filename = "university_records.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv dict writer object
    writer = csv.DictWriter(csvfile, fieldnames=fields)

    # writing headers (field names)
    writer.writeheader()

    # writing data rows
    writer.writerows(mydict)

Running the above code is giving below excel sheet

enter image description here

It contains blank rows as well. How can I remove these blank rows. Thanks

ArtemGr
  • 11,684
  • 3
  • 52
  • 85
S Andrew
  • 5,592
  • 27
  • 115
  • 237

2 Answers2

1

You should create a dataframe with your dict, and then just use

pd.to_csv(name_of_dataframe, sep=your_columns_sep)
arlaine
  • 199
  • 8
  • This is certainly an option. I would not go as far as to say one *should* convert, though. Not everybody is willing to depend on pandas ;) – MB-F Feb 02 '22 at 10:51
  • You're right I should have said you 'could' ahah, but it makes everything so much easier when dealing with excel files I couldn't help myself (: – arlaine Feb 02 '22 at 10:56
1

Adding the newline='' in the with open ... does the trick:

import csv

my_dict = [{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
          {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
          {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
          {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
          {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
          {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]

fields = ['name', 'branch', 'year', 'cgpa']

filename = "foo_bar.csv"

with open(filename, 'w', newline='') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=fields)
    writer.writeheader()
    writer.writerows(my_dict)
Vityata
  • 42,633
  • 8
  • 55
  • 100