Python Tutorial | Python Data File Handling 16

Working with CSV files in Python

Here we will discuss how to load and parse a CSV file in Python.

First of all, what is a CSV ?

CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

For working CSV files in python, there is an inbuilt module called csv.

# importing csv module
import csv

Steps to follow:

1. import the csv module
2. create the fields for the csv file
3.

create the rows of data to be stored in the csv file.(input of values can also be taken and stored in the form of a list)

4 plan the filename of csv file.
5. open the csv file in write mode (“w”).
6. create a csv writer object
example:
csvwriter = csv.writer(csvfile)
7. writing the fields in csv file
example:
csvwriter.writerow(fields)
8. writing the data rows
example:
csvwriter.writerows(rows)

 

Question:1
Python program to create a CSV file named “student.csv”, to store Roll,Name and Per of students.
Sol:

#csv file example
#to create a csv file
# importing the csv module 
import csv 
# field names 
fields = ['Roll', 'Name', 'Per'] 
# data rows of csv file 
rows = [ ['101', 'Nikhil', '99'], 
	 ['102', 'Sanchit', '98'], 
	 ['103', 'Aditya', '98'], 
	 ['104', 'Sagar', '87'], 
	 ['105', 'Prateek', '88'], 
       ] 
# name of csv file 
filename = "student.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)
	

After the execution of the above file, a csv file named “student.csv” gets created. It is an excel file.

 

Question:2
Python program read the contents of CSV file named “student.csv”, and display Roll,Name and Per of students.
Sol:

# importing csv module 
import csv 
# csv file name 
filename = "student.csv"

# initializing the titles and rows list 
fields = [] 
rows = [] 

# reading csv file 
with open(filename, 'r') as csvfile: 
	# creating a csv reader object 
	csvreader = csv.reader(csvfile) 
	
	# extracting field names through first row 
	fields = next(csvreader) 

	# extracting each data row one by one 
	for row in csvreader: 
		rows.append(row) 

	# get total number of rows 
	print("Total no. of rows: %d"%(csvreader.line_num)) 

# printing the field names 
print('Field names are:' + ', '.join(field for field in fields)) 

# printing first 5 rows 
print('\nFirst 15 rows are:\n') 
for row in rows[:15]:
    # parsing each column of a row
    for col in row:
        print(col,end=' ') 
    print('\n') 

Output:

Total no. of rows: 12
Field names are:Roll, Name, Per

First 15 rows are:



101 Nikhil 99 



102 Sanchit 98 



103 Aditya 98 



104 Sagar 87 



105 Prateek 88 



>>>