'I want to create a csv file and then I want to add some data in it

Python As you can see in the CSV Python code I am trying to create a CSV file and then then add some data in it.

import os
import csv

fields = ['Name', 'Branch', 'Year', 'CGPA']

rows = [['Nikhil', 'COE', '2nd', '9.0'],
        ['Karan', 'COE', '2nd', '9.1'],
        ['Aditya', 'IT', '2nd', '9.3'],
        ['Sagar', 'SE', '1st', '9.5'],
        ['Prateek', 'MCE', '3rd', '7.8'],
        ['Sahil', 'EP', '2nd', '9.1']]

filename = "university_reco.csv" as csvfile:
with open(filename, 'w') as csvfile
    csvwriter = file.writer(csvfile)
    csvwriter.writerow(fields)
    csvwriter.writerows(rows)

I thing i am missing something here. so please help me for resolve this problem



Solution 1:[1]

you should write as:

filename="university_reco.csv"

instead of

filename="university_reco.csv" as csvfile:

Solution 2:[2]

You could use Pandas.

import pandas as pd
pd.read_csv(file)

Then work on that dataframe and save it as csv

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html

Solution 3:[3]

This is how you can create csv file with the help of Pytho Pandas library.

import pandas as pd
rows = [('Nikhil', 'COE', '2nd', '9.0'),
        ('Karan', 'COE', '2nd', '9.1'),
        ('Aditya', 'IT', '2nd', '9.3'),
        ('Sagar', 'SE', '1st', '9.5'),
        ('Prateek', 'MCE', '3rd', '7.8'),
        ('Sahil', 'EP', '2nd', '9.1')]
df=pd.DataFrame(data=rows,columns=['Name', 'Branch', 'Year', 'CGPA'])
df.to_csv(file_name, encoding='utf-8', index=False)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 var211
Solution 2 Martín
Solution 3 Anubhav