Notes File Handling Term1 2022-23
Notes File Handling Term1 2022-23
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.
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.
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.
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:
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
What error is returned by the following statement if the file does not
exist?
Ans : FileNotFoundError error
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:
4
line is an
Output:
element
of a List.
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.
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()
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.
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
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
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()
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])
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
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
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
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 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
• 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.
• dump() and load() : Pickle module has two methods - dump( ) to write on file
and load( ) to read from file.
f is a file object
Syntax : pickle.dump(object_to_write,file_object)
Example : pickle.dump(rec,f)
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.
import pickle
def write(): # this is a function to create records on data file.
while True:
roll = input("Enter RollNO. ")
name = input("Enter Name ")
per = float(input("Enter Percentage ")) #Data is input from keyboard
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
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
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()
Output
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
4 Ajay Gupta 88
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:
• 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
elif (ch==2)
search()
….
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:
Rollno,Name,MarksCS
1, Aman, 18
2, Deepika, 19
3, Gagan, 20
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.
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()
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.
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])
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