1
+ import csv
2
+ #read from csv
3
+ fields = list ()
4
+ rows = list ()
5
+ with open ('employee.csv' ,'r' ) as csv_file :
6
+ csv_reader = csv .reader (csv_file )
7
+ fields = next (csv_reader ) #csv reader object
8
+ for row in csv_reader :
9
+ rows .append (row )
10
+ print ("Total no. of rows={}" .format (csv_reader .line_num ))
11
+ print ("Field Names are:" + "," .join (field for field in fields ))
12
+ print ("First 5 rows are:\n " )
13
+ for row in rows [:5 ]:
14
+ for col in row :
15
+ print ("{}" .format (col ),end = " " ),
16
+ print ("\n " )
17
+ #write to csv
18
+ flds = ['Name' ,'Branch' ,'Year' ,'CGPA' ]
19
+ rw = [['Nikhil' , 'COE' , '2' , '9.0' ],
20
+ ['Sanchit' , 'COE' , '2' , '9.1' ],
21
+ ['Aditya' , 'IT' , '2' , '9.3' ],
22
+ ['Sagar' , 'SE' , '1' , '9.5' ],
23
+ ['Prateek' , 'MCE' , '3' , '7.8' ],
24
+ ['Sahil' , 'EP' , '2' , '9.1' ]]
25
+ with open ("university.csv" ,'w' ) as csvfile :
26
+ csvwriter = csv .writer (csvfile )
27
+ csvwriter .writerow (flds )
28
+ csvwriter .writerows (rw )
29
+ #write dictionary to csv
30
+
31
+ mydict = [{'branch' : 'COE' , 'cgpa' : '9.0' ,
32
+ 'name' : 'Nikhil' , 'year' : '2' },
33
+ {'branch' : 'COE' , 'cgpa' : '9.1' ,
34
+ 'name' : 'Sanchit' , 'year' : '2' },
35
+ {'branch' : 'IT' , 'cgpa' : '9.3' ,
36
+ 'name' : 'Aditya' , 'year' : '2' },
37
+ {'branch' : 'SE' , 'cgpa' : '9.5' ,
38
+ 'name' : 'Sagar' , 'year' : '1' },
39
+ {'branch' : 'MCE' , 'cgpa' : '7.8' ,
40
+ 'name' : 'Prateek' , 'year' : '3' },
41
+ {'branch' : 'EP' , 'cgpa' : '9.1' ,
42
+ 'name' : 'Sahil' , 'year' : '2' }]
43
+
44
+ with open ("college.csv" ,'w' ,newline = '' ) as cv :
45
+ fieldnames = ["branch" ,"cgpa" ,"name" ,"year" ]
46
+ writer = csv .DictWriter (cv ,fieldnames = fieldnames )
47
+ writer .writeheader ()
48
+ writer .writerows (mydict )
49
+ with open ("college.csv" ,'r' ) as cvf :
50
+ reader = csv .DictReader (cvf )
51
+ for row in reader :
52
+ print (row ['name' ],row ['branch' ])
0 commit comments