CSV Files 1
CSV Files 1
CSV
Date:27.07.2020 & 28.07.2020
To print digits from a text file
Program Output
f=open('notes.txt','r') 9
c=0 1
for line in f: 2
for i in line: 1
if(i.isdigit()):
0
print(i)
('Total Number of digits:', 5)
c+=1
print("Total Number of digits:",c)
f.close()
Function to count number of lines
starting with letter ‘a’
Program Output
def countlines(): ('Number of lines:', 3)
f=open('notes.txt','r')
c=0 ("Total Number of lines
lines=f.readlines() starting with 'a':", 2)
print("Number of lines:",len(lines))
for w in lines:
if(w[0] in ['a','A']):
c+=1
return c
l=countlines()
print("Total Number of lines starting
with 'a':",l)
CSV Files
• Comma Separated files are delimited files that
store tabular data (i.e. data stored in rows and
columns as we see in spreadsheets or databases).
• The default delimiter of CSV files is the comma (,)
but modern implementations of CSV files allow
you to choose a different delimiter character
other than comma.
• Other delimiters are, colon (:), pipe(I) and semi-
colon (;) characters.
Why CSV Files?
• Easier to create
• Preferred export and import
format for databases and
spreadsheets.
• Capable of storing large amounts
of data.
CSV
• Each line in a CSV file is a data record.
• Each record consists of one or more fields
separated by commas or the chosen delimiter.
• To handle CSV files we use csv module of Python.
This module is helpful for reading and writing in
csv files using csv methods.
• The csv module’s reader and writer objects read
and write delimited sequences as records in a csv
file.
• Import csv statement is mandatory.
Opening/Closing CSV Files
• CSV file is opened in the same way as you open
any other text file.
1. Specify the file extension as .csv
2. Open the file like other text files,e.g.,
f1 = open(“stu.csv”,”w”)
# csv file opened in write mode.
f2 = open(“stu.csv”,”r”)
# csv file opened in read mode.
3. To close the csv file, f1.close()
Writing in csv files - steps
1. Import csv module
2. Open csv file in the file handle.
3. Create the writer object.
4. Obtain user data and form a python
sequence.
5. Write the python sequence containing user
data onto the writer object.
6. Close the file.
Writing in csv files
1. csv.writer() – returns a writer object which
writes data in to a csv file.
2. writerobject.writerow() – Writes one row of
data onto the writer object.
3. writerobject.writerows() – Writes multiple
rows of data onto the writer objects.
writer object is responsible to convert the
received data in to the form (csv–writable–
delimited–form) appropriate for the csv file.
Obtain data from user and write to CSV file
import csv
f1 = open("student.csv","w") #open file
stuwriter=csv.writer(f1) #create writer object with deault
delimiter (,)
#stuwriter=csv.writer(f1,delimiter='|') how to use delimiter
stuwriter.writerow(['RollNo','Name','Marks']) #write header row
for i in range(3):
print("Student Record",i+1)
rn = int(input("Enter rollno:"))
name = input("Enter name:")
marks = float(input("Enter Marks:"))
sturec = [rn,name,marks] #create sequence of user data
stuwriter.writerow(sturec)
f1.close()
User Input
('Student Record', 1)
Enter rollno:123
Enter name:"shemeer"
Enter Marks:25
('Student Record', 2)
Enter rollno:156
Enter name:"rajiv"
Enter Marks:54
('Student Record', 3)
Enter rollno:163
Enter name:"renju"
Enter Marks:46
student.csv
Using writerows() for multiple records
import csv
f1 = open("result.csv","w")
writeobj=csv.writer(f1)
resultdata=[['Name','Marks','Rank'],
['Piyush',88,10],
['Amarnath',85,12],
['Sathyaseelan',84,13],
['Vishnu',90,8]
]
writeobj.writerows(resultdata)
f1.close()
result.csv
Reading in CSV Files
• For reading from a csv file involves loading of csv
file’s data, parsing (i.e. removing its delimitation)
and loading it in a python iterable and then
reading from this iterable.
• Any python sequence that can be iterated over in
a for loop is a python iterable.
Exs: lists, tuples, strings etc.
• csv.reader() – Returns a reader object which loads
data from CSV file into an iterable after parsing
delimited data.
Read from a csv file - steps
1. Import csv module
2. Open csv file in a file handle in read mode.
3. Create the reader object.
4. The reader object stores the parsed data in
the form of iterable, can be fetched from it
row by row using for loop.
5. Process the fetched single row as required.
6. Close the file.
Program to read from csv file
Program Output
import csv ['Name', 'Marks', 'Rank']
with open("result.csv","r") as ['Piyush', '88', '10']
f1: ['Amarnath', '85', '12']
readerobj=csv.reader(f1) ['Sathyaseelan', '84', '13']
for rec in readerobj: ['Vishnu', '90', '8']
print(rec)
f1.close()