Home > Software engineering >  I want to create a csv file and then I want to add some data in it
I want to create a csv file and then I want to add some data in it

Time:05-05

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

CodePudding user response:

you should write as filename="university_reco.csv" instead of filename="university_reco.csv" as csvfile:

CodePudding user response:

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

CodePudding user response:

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)
  • Related