0% found this document useful (0 votes)
38 views

Notes File Handling Term1 2022-23

1. The document discusses text files and binary files. Text files store data in ASCII characters separated by lines while binary files store data in the same format as memory without delimiters between lines. 2. It describes opening, reading, writing, and closing text and binary files in Python. Functions like open(), close(), read(), readline(), readlines(), and write() are used to perform file handling operations. 3. Examples of code snippets are provided to demonstrate creating a text file, writing lines of text to a file, and reading data from a file line by line. Modes like 'r', 'w', 'a' etc. are explained for opening files in read/write/append modes.

Uploaded by

ishan arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Notes File Handling Term1 2022-23

1. The document discusses text files and binary files. Text files store data in ASCII characters separated by lines while binary files store data in the same format as memory without delimiters between lines. 2. It describes opening, reading, writing, and closing text and binary files in Python. Functions like open(), close(), read(), readline(), readlines(), and write() are used to perform file handling operations. 3. Examples of code snippets are provided to demonstrate creating a text file, writing lines of text to a file, and reading data from a file line by line. Modes like 'r', 'w', 'a' etc. are explained for opening files in read/write/append modes.

Uploaded by

ishan arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

File Handling Part 1

Text Files
CBSE SYLLABUS : 2022-23
File handling: Need for a data file, Types of file: Text files, Binary files and CSV (Comma
separated values) files.
● Text File: Basic operations on a text file: Open (filename – absolute or relative
path, mode) / Close a text file, Reading and Manipulation of data from a text file,
Appending data into a text file, standard input / output and error streams, relative and
absolute paths.
● Binary File: Basic operations on a binary file: Open (filename – absolute or relative
path, mode) / Close a binary file, Pickle Module – methods load and dump; Read,
Write/Create, Search, Append and Update operations in a binary file.
● CSV File: Import csv module, functions – Open / Close a csv file, Read from a csv
file and Write into a csv file using csv.reader ( ) and csv.writerow( ).

1. File:- A file is a collection of related data stored in computer storage for future
data retrieval. We need files to store data permanently in Secondary Storage . This
data stored in a file can be used again and again simply by referring to data file name
in the Python program.

2. Stream: - It refers to a sequence of bytes.


3. File handling refers to reading and writing contents from a file.

4. Data Files:
Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line
includes a sequence of characters.

2. Binary Files : A binary file is any type of file that is not a text file.

S.
Text Binary
No.
Files Files
Stores information in the same format
Stores
1. information in ASCII characters.
which the information is held in memory.
Each line of text is terminated with a special
2. No delimiters are used for a line.
character known as EOL (End of Line)
Some internal translations take place when this EOL
3. No translation occurs in binary files.
character is read or written.

Opening and closing a file:

1
Opening a file: To work with a file, first of all you have to open the
file. To open a file in python, we use open( ) function. The open( )
function takes two parameters; filename, and mode.
open( ) function returns a file object.

Syntax: file_objectname= open(filename, mode)

Closing a file:
After performing the operations, the file has to be closed. For this, a close( )
function is used to close a file.
close() function closes the file and frees the memory space acquired by that file. It
is used at the time when the file is no longer needed or if it is to be opened in a
different file mode.

Syntax:

file-objectname.close( )

File Modes:

Text Binary File


file Mode Description
mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file
does not exist.
(Read only
mode)
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not
exist
(Write only
mode)
‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does
not exist
(Append
only mode)
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
(Read and FileNotFound error
write
mode)
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
(Read and
write
mode)
‘a+’ ‘ab+’ Read and write-Append new data

2
(Read and
write
mode)
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file
exists

‘w’ and ‘a’ both modes create new file if the file does not exist

Which of the following error is returned when we try to open a file in


write mode which does not exist?
Ans : NO Error

Identify the invalid mode from the following.


a. a
b. r+
c. ar+
d. w
Ans : ar+

What error is returned by the following statement if the file does not
exist?
Ans : FileNotFoundError error

In addition you can specify if the file


should be handled as binary or text mode Create and Open a file
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)
WORKING WITH TEXT FILES: Read or Write data
Basic operations with files:

a. Read the data from a file Print/Access data


b. Write the data to a file
c. Append the data to a file
Close the file
3
d. Delete a file

a. Read the data from a file:


There are 3 types of functions to read data from a file. Suppose we have
Sample.txt made as :

FUNCTION DOES Usage


THIS
read() To read
entire
data from
file.
Reads till
end of
file Entire data will be read from file and stored in variable named data.

Output:

read(n) It starts
reading
from
wherever
the cursor
is and It reads 5 characters(bytes) from data file.
reads n
bytes Output:

readline() Reads
only 1
line from
file

Output:

readlines() Reads all


the lines
but it
forms a
list. Each

4
line is an
Output:
element
of a List.

See each line is separated by comma, The whole output is


in [ ] denoting a list and wherever we pressed Enter key, it
shows \n

If the file pointer is at the end of 3rd line in a text file


named “data.txt”. readlines() option can be used to read
all the remaining lines

write() It writes
the
f = open("a.txt", 'w')
contents
to the file line1 = 'Welcome to python'
in the f.write(line1)
form of line2="\nPython is fun "
string. It
f.write(line2)
does not
return f.close()
value.

Due to
buffering,
the string
may not
actually
show up
in the file
until the
flush() or
close()
method is
called.

read and readline() both return string.

readlines() returns list

readlines() returns each line as an element of the list- not each word of file as element of list

f1=open("data1.txt","r")
s=f1.read() #reads the whole file data
print(s)

5
Programs
***1. WAP to create a Text File named "Data.txt". Store 2 sentences in the text file.
***
f = open("data.txt", 'w')
line1 = 'Welcome to Class XII A'
f.write(line1+"\n")
line2="Learning Python is useful to me"
f.write(line2+"\n")
f.close()

2. WAP to let the user enter as many lines as he/she wants. Store them in a text file
"data1.txt"

f = open("data1.txt", 'w')
while(True):
s= input("Enter a line ")
f.write(s+"\n")
ch=input("Do you wish to enter More lines Y for yes
")
if ch=='n' or ch=='N':
break
Output:
Data1.txt

6
1. Access the Text File data2.txt, display all the Contents of data2.txt

fileobj= open("data2.txt","r")
x=fileobj.read()
print(x)
fileobj.close()

 If your program is in the same  All data in data2.txt is displayed.


folder as data file-then there is no
need to give the path of the file in
fileobj.open statement.
 If data file is present in some
other folder, simple go to data file’s
properties, copy path and paste it in
the Python Program where you are
opening the data file.

2. Access the Text File data2.txt, display first 5 characters of data2.txt and then
next 5 characters

fileobj= open("data2.txt","r")
x=fileobj.read(5)
print(x)

x=fileobj.read(5)
print(x)

fileobj.close()
3. Access the Text File data2.txt, display first line and then access second line and
display it

fileobj= open("data2.txt","r")
x=fileobj.readline()
print(x)

x=fileobj.readline()
print(x)
Reads first line, displays it. Then
fileobj.close()
automatically file pointers reads next line
and displays it.
4. Access the Text File data2.txt, add 2 lines “Python is interesting” and “Good we
are learning this”)

fileobj= open("data2.txt","a")
#see we are using append mode
fileobj.write("Python is
interesting\n" )

7
fileobj.write("Good we are
learning it\n" )
fileobj.close()

fileobj= open("data2.txt","r")
x=fileobj.read()
print(x)
fileobj.close()
5. WAP to access a Text File named "Data2.txt". Display the number of uppercase
letters, no of digits, number of words, no. of vowels in the file.**

f1=open("data2.txt","r")
s=f1.read() Data2.txt:
L= len(s)
countucase=0 I like Computers
countdig=0 123
countblank=0 Python is fun.
countvowel = 0
for i in range(0,L): Output:
ch= s[i]
No. of Uppercase characters 3
if ch.isupper(): No. of Digits 3
countucase= countucase+1 No. of words 7
if ch.isdigit(): No. of vowels are 9
countdig= countdig+1
if ch.isspace():
countblank= countblank+1
ch=ch.upper()
if ch =='A' or ch=='E' or
ch=='I' or ch=='O' or ch=='U':
countvowel= countvowel+1
print("No. of Uppercase
characters ",countucase)
print("No. of Digits ",countdig)
print("No. of words
",countblank+1)
print("No. of vowels are
",countvowel)
6. WAP to access a Text File named "Data2.txt". Display the number of lines in the
file
f1=open("data2.txt","r")
s=f1.readlines()
L= len(s)
print(L)

7. WAP to access a Text File named "Data3.txt". Split the file into words. Store
words in a List. Display the List. Traverse each word at a time of list and display
it in separate line.

# data3.txt has text : List with words:


I like Computers 123
Python is fun ['I', 'like', 'Computers', '123',
'Python', 'is', 'fun.']

8
fileobj=open("data3.txt","r") Traversing the List:
s=fileobj.read()
list1=s.split() I
like
print("List with words: ") Computers
123
print(list1) Python
is
print("\n Traversing the fun.
list")

L=len(list1)
for i in range(0,L):
print (list1[i])
8. WAP to access a Text File named "Data3.txt". Split the file into words. Store
words in a List. Display number of words in the text file.

Output
fileobj=open("data3.txt","r")
s=fileobj.read() List with words:
list1=s.split() ['I', 'like', 'Computers', '123', 'Python', 'is',
print("List with words: ") 'fun.']
print(list1)
L=len(list1) number of words are: 7

print("\n number of words


are: ", L)
9. WAP to access a Text File named "Data3.txt". Count number of times ‘is’ occurs
in the file data3.txt # we can solve any program related to words using this#

List with words:


['I', 'like', 'Computers', '123', 'Python', 'is',
'fun.', 'Computers', 'are', 'useful']
fileobj=open("data3.txt","r")
c=0
s=fileobj.read() No of times -is- occurs in data file is 1
list1=s.split()
L=len(list1)
for i in range (0,L):
if list1[i]=="is":
c=c+1
print("No of times -is-
occurs in data file is ",c)
10. WAP to access a Text File named "Data3.txt". Count number of times ‘is’ and
number of times ‘Computers’ occurs in the file data3.txt. Use count function of
Python

f=open("data3.TXT") Count of -is-: 1


s=f.read() Count of -COMPUTERS-: 2
f.close()

9
L=s.split()
c1=L.count("is")
c2=L.count("Computers")
print("Count of -is-:",c1)
print("Count of -COMPUTERS-
:",c2)
11. WAP to access a Text File named "Data3.txt". Replace with blank with “#” and
store it in a new file

file1 = open("data.txt","r") Suppose data.txt has


file2 = open("temp.txt","w")

St = file1.read()
for i in St:
if i ==' ':
file2.write('#') temp.txt
else:
file2.write(i)

file1.close()
file2.close()
The above Program may be written like this :

file1 = open("data.txt","r")
file2 = open("temp.txt","w")

St = file1.read()
size=len(St)
for i in range(0,size):
if St[i] ==' ':
file2.write('#')
else:
file2.write(St[i])

file1.close()
file2.close()
12. WaP to access the file data.txt. Read all the lines and
display the list with lines.
f = open("data.txt", [‘Python is fun’, ‘I am studying
'r') useful’]
text = f.readlines()
print(text )
f.close()

13. Access the file “data.txt”. Add 12 A and name of school


at the end.
file1 = open("data.txt","a")
file1.write("12 A\n")
file1.write("MJKPS")

10
file1.close()
14. Access data.txt. Display those lines that start with “P”
f1=open("data.txt","r")
s=f1.readlines()
print(s)
for i in range(0,len(s)):
if(s[i][0]=='P'):
print(s[i])

Using seek() and tell()


Seek() is used to set the file’s current position at the
offset.

fileObject.seek(offset, whence])
Parameters
 offset − This is the position of the read/write pointer within the file.
 whence − This is optional and default is which means absolute file positioning
Other values are 1 which means seek relative to the current position
2 means seek relative to the file's end.

SNO Code
1. f1.seek(5,0) # positions at 6th characater, Will
now read starting from 6th characters

print(f1.read()) # will print entire file starting


at 6th character incl 6th character

2. f1=open("data1.txt","r")
s=f1.read() #reads the whole file data
print(s)
f1.seek(5,0) # positions at 6th characater, Will
now read starting from 6th characters

print(f1.readlines()) # will print entire file


starting at 6th character incl 6th character. Will
return each line as an element of list.

Example : ['dy\n', 'Computers and Software\n',


'123\n']

3 f=open("datanew.txt",'w')
f.write("Hello\n")
f.write("Welcome to my Blog")

11
f.close()

f=open("datanew.txt",'r')
print(f.readline()) # will print Hello
print(f.tell()) # will print 7 as it adds 2 char for \n
print(f.readline()) #will print "Welcome to my Blog"
print(f.tell()) # will print 25
4
f=open("datanew.txt",'w')
f.write("Hello\n")
f.write("Welcome to my Blog")
f.close()

f=open("datanew.txt",'r')
f.seek(7,0)
print(f.read()) #will print "Welcome to my Blog

print(f.readline()) #will not print anything as


end of file was reached.

5 f=open("datanew.txt",'r')
f.seek(7,0)
print(f.read()) #will print "Welcome to my Blog
f.seek(0) #will position file pointer to
beginning
print(f.readline()) #will print Hello

Relative and Absolute Paths :


 We all know that the files are kept in folders.
 Every running program has a current directory. Which is generally a default
directory and python always see the default directory first.
 The absolute paths are from the topmost level of the directory structure. The
relative paths are relative to the current working directory denoted as a dot(.)
while its parent directory is denoted with two dots(..).
 OS module provides many such functions which can be used to work with files and
directories. OS means Operating System.
 getcwd( ) is a very function which can be used to identify the current working directory
>>> import os
>>> cwd=os.getcwd()
>>> print(cwd)

 Relative Path is the location of file/folder from the current folder. To use Relative
path special symbols are:
 Single Dot ( . ) : single dot ( . ) refers to current folder.
 Double Dot ( .. ) : double dot ( .. ) refers to parent folder

12
 Backslash ( \ ) : first backslash before(.) and double dot( .. ) refers to ROOT folder.

Absolute path:

C:\Users\Nancy\Appdata\Local\Programs\Python39\Python

STANDARD FILE STREAMS :


• We use standard I/O Streams to get better performance from different I/O devices.
• Some Standard Streams in python are as follows –

– Standard input Stream sys.stdin


– Standard output Stream sys.stdout
– Standard error Stream sys.stderr

File Handling Part 2- Binary File Handling


CBSE Syll :
Binary File: Basic operations on a binary file: Open (filename – absolute or
relative path, mode), Close a binary file, Pickle Module – methods load
and dump; Read, Write/Create, Search, Append and Update operations
in a binary file.

• Binary files are files formatted without readable characters, and can range
from files for data records, images, audio files, PDFs, etc.

• Pickle: If we want to write structure such as list, dictionary etc and also we

13
want to read it then we have to use a module in python known as pickle.

Pickle is a Module

• Pickling: What pickle does is that it “serializes” the object first before
writing it to file. Pickling is a way to convert a python object (list, dict, etc.)
into a character stream so that it can be written on a file.

• UnPickling: And when we read a file then a opposite operation is to be done


means unpickling.

• dump() and load() : Pickle module has two methods - dump( ) to write on file
and load( ) to read from file.

 Any object in Python can be pickled so that it can be saved on disk.


 In Python, a physical file must be mapped to a built-in file object with the
help of built-in function open(). f is file object and Studentfile.dat is
physical file.
f=open("Studentfile.dat","wb")

f is a file object

 pickle .dump() : To write the Object into the file

Syntax : pickle.dump(object_to_write,file_object)
Example : pickle.dump(rec,f)

 pickle .load() : To read the Object from the file Syntax :


container_obj=pickle.load(file_object)
Example rec = pickle.load(f)

Operations that can be done on files.-


• Creating of Files
• Traversing of Data in file
• Appending Data into file.
• Inserting Data into File.
• Deleting Data from File.
• Copying of File.
• Updating Data into File.

 Opening a file: Before we can read or write a file, we have to open it using
Python's built-in open() function. This function creates a file object

14
 The open() function opens a file in text format by default.

 To open a file in binary format, add 'b' to the mode parameter. Hence the
"rb" mode opens the file in binary format for reading, while the "wb" mode
opens the file in binary format for writing.

 Closing a file: The close() method of a file object flushes any unwritten
information and closes the file object, after which no more writing can be
done.
 Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.
Program
Writing onto a file students records. Name of the file is “Studentfile.dat”. Each record has
Rollno, Name, Percentage.

Writing Records to a File

import pickle
def write(): # this is a function to create records on data file.

f=open("Studentfile.dat","wb") #wb means write mode, binary file

while True:
roll = input("Enter RollNO. ")
name = input("Enter Name ")
per = float(input("Enter Percentage ")) #Data is input from keyboard

rec = [roll,name,per] # we put the data in a listnamed rec


pickle.dump(rec,f) # will dump the record rec in file. F is file object

ch=input('Enter more records Y/N ')


if ch=='N'or ch =='n':
break # break takes control out of loop
f.close()

Reading a file

15
def read():
f=open("Studentfile.dat","rb")
try:
while (True):
rec=pickle.load(f) # keep on reading and storing list called rec and print the record

print(rec) #load and dump are functions of pickle module.

except EOFError: #the moment eof is reached, exception is executed and file is closed.

f.close()
------------------------
Calling functions
write() #calling the functions
read()

Note:
dump has 2 arguments- record, fileobject
load has one argument- fileobject

Appending Records in the file

def append(): # append means adding to the end of file


f=open("Studentfile.dat","ab") # a is for append, b is for
binary

while True:
roll = input("Enter RollNO. ")
name = input("Enter Name ")
per = float(input("Enter Percentage "))
rec = [roll,name,per]
pickle.dump(rec,f)
ch=input('Enter more records Y/N ')
if ch=='N'or ch =='n':
break

16
f.close()

Searching for a Record


Rollno will be entered by user. His/her record will be displayed
def search():
r= input("Enter Rollno of Record to be searched: ")
# if in your datafile, rno is integer, then convert.
f=open("Studentfile","rb")
try:
found = 0
while (True):
rec=pickle.load(f) # loads one record in RAM from f file and stores in rec
variable as a List. Next time when this is executed, next record is read.

if rec[0]==r : #rec[0] means first column/element ie.


rollno
print(rec)
found = 1
# found is just a flag
except EOFError:
if found==0:
print("Record Not Found")
f.close()

Output

Enter Rollno of Record to be searched: 3


['3', 'Yashika', 34.0]

Enter Rollno of Record to be searched: 7


Record Not Found

Searching for a Record when Name is input by the user.

Deleting a Record whose Roll No is input

17
def delete():
r= input("Enter Rollno of Record to be deleted")
f=open("Studentfile","rb") # open this file in read mode
f2=open("tempfile","wb") # open this file in write mode
try:
found = 0
while (True):
rec=pickle.load(f)
if rec[0]==r : #checking if rollno same as that to be deleted

found = 1
else:
pickle.dump(rec,f2)
except EOFError:
f.close()
f2.close()
os.remove("Studentfile") #we have to use import os
os.rename("tempfile","Studentfile")

Output:
['1', 'Siddharth Sharma', 98.7]
['3', 'Yashika', 34.0]
Enter Rollno of Record to be deleted :3
Contents of file after Deletion are
['1', 'Siddharth Sharma', 98.7]

Enter Roll no : 3

18
Studentfile tempfile

1 Amit Sharma 78.9 1 Amit Sharma 78.9

3 Damini 67 4 Ajay Gupta 88

4 Ajay Gupta 88

Updation/Modification of a Record whose Roll No is input


def modify():
r= input("Enter Rollno of Record to be modified")
f1=open("Studentfile","rb") # opened in read mode
f2=open("tempfile","wb") # opened in write mode
try:
found = 0
while (True):
rec=pickle.load(f1)
if rec[0]==r : # rec[0] is rollno part of record
found = 1
roll = input("Enter new RollNO. ")
name = input("Enter new Name ")
per = float(input("Enter new Percentage "))
rec = [roll,name,per]
pickle.dump(rec,f2) # in f2 file(tempfile) we store new record

else:
pickle.dump(rec,f2) # in f2 file(tempfile) we store old record only

19
except EOFError:
f2.close()
f1.close()
print("Contents of file after Modifications are")
f2=open("tempfile","rb")
f2.seek(0)
try:
while (True):
rec=pickle.load(f2)
print(rec) # displaying records of temporary file
except EOFError:
f2.close()
os.remove("Studentfile")
os.rename("tempfile","Studentfile")

Output:

['1', 'Siddharth Sharma', 98.7]


Enter Rollno of Record to be modified1
Enter new RollNO. 100
Enter new Name Sidharth Sharrma
Enter new Percentage 78.9
Contents of file after Modifications are
['100', 'Sidharth Sharrma', 78.9]

Relative and AbsolutePaths

• We all know that the files are kept in directory which are also known as
folders.
• Every running program has a current directory. Which is generally a default
directory and python always see the default directory first.
• OS module provides many such functions which can be used to work with files
and directories. OS means Operating System.

20
• getcwd( ) is a function which can be used to identify the
current working directory.

Assignment
Create a menu driven program

print(“1 – create a file ")


print(“2 – search and display a record ")
print(“3 – delete a record ")
print(“4 – update a record ")
print(“5– append a record ")
input(“ “)
if(ch==1)
add()

elif (ch==2)
search()
….

 tell()function returns the current position of file pointer.


 seek(-10, 1) will move 10 bytes back from current pointer

21
 When we open file in append mode the file pointer is at the end of the file.
 In file/variable/keyword file, data is stored permanantly
 open( ) function takes ____ as parameter. (filename, filemode)
 By default file opens in read mode
 In __________mode, if the file doesn’t exist, then a new file will be
created” and “After opening file in that mode the file handle will be at the
end of the file” (append)
 There are 2 valid open() ways:
i)with open (file_name, access_mode) as f:

ii)f = open (file_name, access_mode)

File Handling Part 3- CSV files


CBSE Syllabus:
CSV File: Import csv module, functions – Open / Close a csv file, Read from a csv file and
Write into a csv file using csv.reader ( ) and csv.writerow( ).

1. CSV stands for Comma Separated values files. Example : 1, Aman,18


2. Delimiter used (usually a comma)
3. They are stored as text files
4. They are used to store large amount of data.
5. Rows and Columns way…large data….csv used. Each row represent record.
6. Any programming language that stores text, can store csv files.
7. Each file has rows. Values separated by commas.Ex : CSV file:

 Rollno,Name,MarksCS
 1, Aman, 18
 2, Deepika, 19
 3, Gagan, 20

8. Very advantageous as CSV files can be exported to other files.


9. CSV files can be converted to other databases types and can be converted
from them to CSV files.
10. IN Text files, file can be opened with Text Editor. IN CSV special character
is a delimiter, Can be a comma, *
11. First line in CSV file is a heading of row

22
12. Generally when we open a CSV files, it opens in Google sheets. And
converts columns based on commas into separate columns
13. Data in CSV files is stored as text.
14. csv module is used to write data in csv file
15. csvwriter() function is used to write object in file
16. csvwriterow() function is used to insert rows in a csv file.
17. Records can be written in the form of lists or dictionary but in our course
we have lists in csv file

Csv is a module.

Writing Records in CSV file


1. **WAP to let the user enter details of employees (email id, name,
phone,salary) and store in csv file**

import csv

def write():
f= open("data.csv","w")
rec= csv.writer(f,delimiter=',')
rec.writerow( ['EMPID','NAME','EMAIL ID',
'PHONE','SALARY'])
while True:
empid= input("Enter Employee Id ")
name= input("Enter name")
emailid= input("Enter email id ")
phone= input("Enter Phone")
salary=int(input("Enter Salary "))
r=[empid,name,emailid,phone,salary] #list
created
rec.writerow(r) # one record is written
in csv file
ch= input("want to input more data ")
if ch=='n' or ch=='N':
break

write()

Reading a CSV file


1. CSV module used
2. csv,reader() used to read records from a csv file
3. records read are in the form of a list.
4. records can be read into a dictionary be csv,DictReader() function
5. Pandas library can be used. They provide excellent data analysis

Program 2: WAP to Access the CSV file “data.csv”. Display all records.

23
2. Read each record of csv file data.csv. Display it

import csv
def read():
with open("data.csv","r") as f:
rec= csv.reader(f) #reads next record each time from
file
for i in rec:
print(i)

read()
Output:
'EMPID', 'NAME', 'EMAIL ID', 'PHONE', 'SALARY']
['101', 'Gagan', '[email protected]', '657890564', '50000']
['102', 'Harshita', '[email protected]', '789065432', '60000']

3. Searching in the CSV file “data.csv”. Display those records which have salary above
50000.
import csv
def search():
with open("data.csv","r") as f:
rec= csv.reader(f)
next(rec) # first record is of heading. We skip that
for i in rec:
if int(i[4]) >50000:
print(i)

search()
Newly Added Part
Difference between r+ and w+ in open()

1. If the file does not exist, r+ throws FileNotFoundError; the w+ creates the file.
2. If the file exists, r+ opens it without truncating; the w+ truncates the file and
opens it.

Difference between w+ and a+ in open()


Below is the difference between w+ and a+:
If the file exists, w+ truncates the file and opens it; a+ opens it without truncating.
For w+ mode, the initial file pointer position at the beginning of the file; For a+ mode, the
initial file pointer position at the end of the file.

Difference between r+ and a+ in open()

1. If the file does not exist, r+ throws FileNotFoundError; the a+ creates the file.
2. For r+ mode, the initial file pointer position at the beginning of the file;
For a+ mode, the initial file pointer position at the end of the file.

24
seek and Tell()
Python file method seek() sets the file's current position at the offset.
fileObject.seek(offset[, whence])

The whence argument is optional and defaults to 0,


Whence 1 means seek relative to the current position
Whence 2 means seek relative to the file's end.

f=open("datanew.txt",'w')
f.write("Hello")
f.write("Welcome to my Blog")
f.close()

f=open("datanew.txt",'r')
d=f.read(5)
print(d) # First Print Statement will print Hello
f.seek(10) # read 10 bytes from beginning.Now 11th byte will be read
d=f.read(3)#will read me
print(d) # Second Print Statement will print me
f.seek(13) #will read 13 characters. Now it will read 14th character
d=f.read(5) #will read to my
print(d) # Third Print Statement will print to my
d=f.tell() #Now its at 18th character.
print(d) # Fourth Print Statement will print 18

25

You might also like