0

I was learning to write a .csv file. I ran the code of this site https://www.geeksforgeeks.org/writing-csv-files-in-python/
I ran the code and found that there is an extra row gap after each row which I don't want. The code is as follows:

# Python program to demonstrate
# writing to CSV


import csv
    
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
    
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
        ['Sanchit', 'COE', '2', '9.1'],
        ['Aditya', 'IT', '2', '9.3'],
        ['Sagar', 'SE', '1', '9.5'],
        ['Prateek', 'MCE', '3', '7.8'],
        ['Sahil', 'EP', '2', '9.1']]
    
# name of csv file
filename = "university_records.csv"
    
# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)
        
    # writing the fields
    csvwriter.writerow(fields)
        
    # writing the data rows
    csvwriter.writerows(rows)

I am getting output as follows: output after running above code

I want to get output something like this: Output expected

I need to write csv files for a very big dataset therefore it can't be done manually. I need inputs so that writing csv files can be coded. Thanking in advance!!

Avii
  • 164
  • 12
  • 1
    That's odd, I copied your code exactly and got the correct result with no spaces. Maybe something to do with the reader you are using? Edit: I think @PacketLoss is correct. I am running on linux. Possibly has to do with the line endings in windows. – Kyle Dixon Oct 22 '21 at 15:42
  • Interesting that the [referenced tutorial](https://www.geeksforgeeks.org/writing-csv-files-in-python/) even states "A csvfile object should be opened with newline='' otherwise newline characters inside the quoted fields will not be interpreted correctly" and then the actual example doesn't do it. – Mark Tolonen Oct 24 '21 at 05:55

0 Answers0