CVS File Handlinng
CVS File Handlinng
CVS File Handlinng
CSV files are simple text files has csv as extension (.csv). These files are important when we
want to store the data in tabular form as data is saved in excel /sql ( in form of rows and
columns).
Unlike binary files, in csv files data can be easily readable either in excel (tabular form) or in
text editor ( data is separated by comma).
In csv file, each line of the file is data record and each record consists of one or more fields.
For eg:
Train number Train Name Boarding Last stop Boarding Time
12962 Avantika Exp Indore Mumbai 4:15pm
Note: The CSV files are opened in Excel by default and after opening in Excel the data of file
is automatically shown in different columns.
Writing CSV files in Python : To work with csv files in Python, we import csv module:
Writing CSV file using CSV module File 'Innovators.csv' is opened in 'w' file
mode.
import csv To avoid empty line between records,
f=open('Innovators.csv', 'w', newline='') we use newline attribute assign with
w= csv.writer(f) empty string.
Fields = ['Sno', 'Name', 'Contribution'] For writing in csv file, first create a
First = [1, 'Dennis Ritchie' , 'C'] writing handle.
Second =[2, 'Bjarne Stroustrup', 'C++' ] To create a writing handle, we use
Third =[3, 'Guido Van Rossum', 'Python'] writer() function that returns the writer
w.writerow ( Fields) object which writes data into csv file.
w.writerow ( First) Create lists with data.
w.writerow ( Second) writerow() function writes a row of
w.writerow ( Third) data into the specified file.
f.close() Close() the file.
Writing multiple rows using writerows()
function
import csv • This code writes header(column
records= [['Sno', 'Name', 'Contribution'], name) and three records in the file
[1,' ', 'Dennis Ritchie' ,' ', 'C'], using writerows() function in a one
[2, 'Bjarne Stroustrup', 'C++' ], shot.
[3, 'Guido Van Rossum', 'Python']]
f=open('Innovators.csv', 'w' , newline='')
w= csv.writer(f)
w.writerows(records)
f.close()
Reading from csv file:
with open('firstfile.txt','w') as f:
f.write ('To open a file using with keyword\n')
f.write ('There is no need to close the file explicitly\n')
f.write ('when open with "with" keyword')
>>>
To open a file using with keyword
There is no need to close the file explicitly
when open with 'with' keyword