File Handling Notes
File Handling Notes
File is a document stored on a permanent storage device which can be read, written or rewritten according to
our requirement. Data maintained inside the files is persistent data.they store data pertaining to a specific
application
TYPES OF FILES
Textfile
Binary file
CSV(Comma separated values) files
Text file : stored information in the form of stream of ASCII code or Unicode on permanent storage media. Each
line is terminated with specialcharacter EOL(end of line). some internal translation takes place like EOL
character into \n(newline character ) or (\r) carriage return when this Text files are stored in human readable
format. CSV(comma separated values ) is a kind text file.
Opening a file :
File_object = open(“filename.txt”,filemode)
For example : f = open(“story.txt”,’r’)
Where f is a file object or handler which is used to give reference to file on disk for reading , writing data or performing
other function on file.
Even you can give full path as : f = open(“c:\\project\\story.txt”,’r’)
F = open(r”c:\project\story.txt, ’r’)
Here r in front of a string makes it raw string that means there is no special meaning attached to any character
These ways of opening a file is important from MCQ point of view
Closing of file : In python files are automatically closed at the end of the program but it is good practice to close a file
because of the following reasons :
1. Sometimes data written using write functions remains in the memory until the next write operation or the file gets
closed.this may leads to loss of data. So closing a file means data is permanently transferred to file from memory.
2. closing a file will releases a resources allotted to it by operating system for other files and make system run faster.
For example : f.close()
File mode : these modes governs the type of operation(i.e. read ,write or append) possible on the opened file
2. readline() -read a line of input,if n is specified read at most n bytes . and returns bytes in the form of string
ending with ‘\n’.
Fileobject.readline()
Program to read first line only
f=open('Student.txt','r')
content=f.readline()
print(content)
f.close()
Output
Nakul Dev Gaurav
f=open('Student.txt', 'r')
content=f.readline()
print(content)
print("Reading next line")
content=f.readline()
AMIT KUMAR KUSHWAHA (9891145409) 2
print(content)
f.close()
Output
Nakul Dev and Gaurav
Reading next line
study in class 12th.
3. readlines() : read all lines and return list
Program to read all the lines
f=open('test.txt', 'r')
content=f.readlines()
print(content)
f.close()
Output :['Nakul Dev and Gaurav\n', 'study in class 12th.']
Program to calculate size of file
f=open('test.txt','r')
content=f.read()
size=len(content)
print(“Size of the file is: ”, size)
f.close()
Output : Size of the file is: 40
Program to calculate number of lines in a file
f=open('test.txt', 'r')
content=f.readlines()
size=len(content)
print(“Number of lines in the file is: ”, size)
f.close()
Output
Number of lines in the file is: 2
Note : to read data word by word we have to read data from files using any of the above method and then we have
to use spilt() function to separate them in words.
Writing to a file
Various methods for writing to a file are asfollows:
write(string) : fileObject.write(string)
writelines(lst) : fileObject.writelines(lst)
flush () function : python holds everything to write in the file in buffer and pushes it into actual file on storage device later
time.if however if you want to force the writing of data on file from buffer before closing a file you can use flush function .
syntax : fileobject.flush()
The absolute path (also known as the full path) of an file or entity contains the complete information
(from the root to the ending) needed to locate it. The absolute path is not affected by the user’s current
working directory, and it always includes the root directory as a starting point.
For example the absolute path of book.txt will be “d:\python\program\book.txt”
The relative path of an entity contains the information needed to locate that entity relative to the user’s
current working directory. The relative path disregards the information needed to locate the current working
directory from the root directory and only focuses on the route from the working directory to the entity.
For example if the current working directory is “d:\python\programs” then the relative path of book.txt in
the same folder is just “book.txt” .Similarly the relative path of “chapters.txt” in subfolder chapter1 will be
“chapter1\chapters.txt” . A relative path can use ‘...’ to refer to the parent folder of the current working
directory.
For example if he current working directory is “D:\python\program” then the relative path of book.txt will
be “...\book.txt”
Programs : Line by line
Q-Define a function EXECUTE() that will read a text file demo.txt. The function willcount total
number of lines not starting with ‘P’.
Coding:
def EXECUTE():
f=open("demo.txt",’r’)
cnt=0
Line=f.readlines()
for i in Line:
if i[0]!="P":
cnt+=1
print(“Total number of lines not starting with ‘P’ is ”,cnt)f.close()
EXECUTE()
demo.txt:
Python is very interesting.
It is a high level programming language.It was
developed by Guido Van Rossum.
Output:
Total number of lines not starting with ‘P’ is 1
Q Define a function EXECUTE() that will read a text file demo.txt and count the totalnumber of
words present in that file.
def EXECUTE():
f=open("demo.txt")cnt=0
Line=f.readlines()
for i in Line.split():
cnt=cnt+1
print("Number of words ,",cnt)f.close()
EXECUTE()
demo.txt:
Python is very interesting.
It is a high level programming language.It was
developed by Guido Van Rossum.
Output:
Number of words 18
Q. Define a function EXECUTE() that will read a text file demo.txt and will copy allthose words
who are in length four or more to another file info.txt
Coding:
def EXECUTE():
f1=open("demo.txt")
f2=open("info.txt", 'w')
Line=f.read()
for words in line.split:
if len(words)>=4:
f2.write(words)
f1.close()
f2.close ()
EXECUTE()
demo.txt:
Python is very interesting.
It is a high level programming language.It was
developed by Guido Van Rossum.
Output (info.txt): Python very interesting.high level programming language.developed Guido Rossum.
Q- Write a function remove_lower case() that accepts two file names and copy all file lines that do
not start with a lowercase letter from the first file into the second file.
def remove_lower() :
f=open("demo.txt",'r')
y=open("info.txt",'w')
Line = f.readlines()
for i in Line:
if i[0].islower():
y.write(i)
f..close()
y.close()
remove_lower()
Q-Define a function execute() that will read a text file demo.txt. This function will printjust the last line of this
text file.
BINARY FILE : Python Objects like list and dictionary are first serialized(means converted into stream of
bytes ) and then stored in binary file.There is no delimiter for a line, no character translation. Binary files
are easier and faster than text files for carrying reading and writing operations.we have to import module
pickle to work with binary files.
Pickling or Serialization : process of converting the Python Objects into a stream of bytes before writing to
the file
Unpickling or deserialization : means converting back stream of bytes into python object
Opening of file is same as text file we just have to use files mode with suffix as b
Example : f=open (“student.dat”,’wb’)
DUMP METHOD: Used to write data into a binary file
import pickle
def write():
list1=[10, 20]
f=open("Test2.dat", 'wb')
pickle.dump(list1, f)
print("Data is written to binary file.")
f.close()
write()
LOAD METHOD: Used to read data from a binary file
import pickle
def read():
data = [ ]
f=open("Test2.dat", 'rb')
data=pickle.load(f)
print (data)
f.close()
Random access in files using tell() and seek()
pickle.load () function would raise EOFError while reading a file so there are two ways to handle this
problem
Try and except block : this block will capture runtime exception
For example :
def display():
emp=[]
f= open('employee.dat','rb')
try :
print("file stores these records")
while True:
emp = pickle.load(f)
print(emp)
except EOFError:
f.close()
2. Using with statement: this statement is compact statement which includes opening and processing of
file together
Difference with normal opening of file : when we open file using with statement we need not to close the
file and also it will trap EOF exception automatically
For example :
def display():
emp=[]
with open('employee.dat','rb') as f:
print("file stores these records")
emp = pickle.load(f)
print(emp)
f.close()
Write a menu driven program to add display and modify record of a member of club. update
club.dat file with new increased value of member number
Member = [Mno, Mname,Type]
import pickle
def ADD():
rec=[]
f=open("Club.dat",'ab')
CSV file
‘Comma Separated Values’ file
Used to store tabular data in a database.
Comma separated file is delimited text file that uses a comma toseparate values
Each line is a record
Smaller in size
Human readable and easy to edit manually
Faster to handle
Note : in CSV files you can now change default delimiter i.e. comma
We have to import CSV module which provide functionality to read and write tabular data in CSV format
Opening of CSV file is same as text file except extension of file will be .csv
Write a program in python that defines and calls the following user defined functions
i. COURIER_ADD() : It takes the values from the user and adds the details to a csv file
‘Courier.csv’.Each record consists of a list with field elements as Cid,S_name,Source and
Destination to store Courier ID,Sender name ,Source and destination address respectively
ii. COURIER_SEARCH() : takes the destination as the input and display all the courier records
going to that destination
Coding:
import csv
def COURIER_ADD():
C=[ ]
F=open(“Courier.csv”,’a’,newline = “”) // newline will suppress EOL translation
CW=csv.writer(F,delimter = “!” ) // used to change default delimiter i.e.’,’
CW.writerow(‘CID’,’Sender name’,’Source’,’Destination’) // to write column header
ans=’y’
while ans == ‘y’:
C_id=int(intput(“Enter customer id ”))
S_name = intput(“Enter sender name ”)
Source = intput(“Enter source ”)
Destination = intput(“Enter destination to send ”)
C=[C_id,S_name,Source,Destination]
CW.writerow( C)
ans= input(“Do you want to continue(y)”)
if ans !=’y’:
break
F.close()
def COURIER_SEARCH():
C=[ ]
Dest=input(“Enter destination to search for courier”)
with open(“Coureir.csv”,’r’) as F:
C=csv.reader(F)
Found=0
for rec in C:
if rec[3] == Dest:
print(rec)
Found=1
if Found = 0:
print(“Record not found”)
// statement to call the above function
COURIER_ADD()
COURIER_SEARCH()