0% found this document useful (0 votes)
49 views10 pages

File Handling Notes

Uploaded by

saiyansh mahajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views10 pages

File Handling Notes

Uploaded by

saiyansh mahajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

PRATIBHA GUPTA CLASSES

6/13 GROUND FLOOR WEST PATEL NAGAR


MOB: 9811483470,9873220575,011-41838070
NOTES :FILE HANDLING (XII)

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

Text file or csv file mode Binary file mode


‘r’ ‘rb’ Used for reading from a file .by default file always opened in
read mode

AMIT KUMAR KUSHWAHA (9891145409) 1


‘w’ ‘wb’  Used to create a file
 If the file doesn’t exist ,file is created
 If the file exist ,it will truncate existing data and overwrite
in the file.
‘a’ ‘ab’  File is in write only mode
 If the file exists,the data in the file is retained and new
data being written will be appended to the end
 If the file doesn’t exist ,it will create the new file
‘r+’ ‘rb+’ Both reading and writing operation take place but for this
mode file must exist otherwise it will generate error message
‘w+’ ‘wb+’  File is created if doesn’t exist.
 If exist it will be truncated
 Both writing and reading operation take place
‘a+’ ‘ab+’  If the file exists,the data in the file is retained and new
data being written will be appended to the end
 If the file doesn’t exist ,it will create the new file
 Both writing and reading operation take place

Reading data from text file


1. Character by character :
f.read(n) - will read n character from file. If no n is specified it will read whole file and returns the read bytes in the
form of string.
For example file name is students.txt contains data : “Nakul Dev and Gaurav
study in class 12th”.
Program to read complete content of thefile using read() function
f=open('student.txt', 'r')
content=f.read()
print(content)
f.close()
Output
Nakul Dev and Gaurav study in class 12th.

Program to read first letter only


f=open('Student.txt', 'r')
content=f.read(1)
print(content)
f.close()
Output : N

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)

Program to write your name in file


f=open('test.txt', ‘w')
f.write(“Karishma”)
print(“Data written infile.”)
f.close()
Output : Data written in file.
Program to write and read 5 names input from user in file
f=open('test.txt', 'w+')
for n in range(3):
name=input("Entername:")
f.write(name)
f.write("\n")
f.close()
f=open('test.txt','r')
print("Names written in file.")
content=f.read()
print(content)
f.close()

AMIT KUMAR KUSHWAHA (9891145409) 3


Output
Enter name:Ab
Enter name:Cd
Enter name:Ef
Names written in file.
Ab
Cd
Ef

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()

ABSOLUTE AND RELATIVE PATHNAME

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.

AMIT KUMAR KUSHWAHA (9891145409) 4


Coding:

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()

AMIT KUMAR KUSHWAHA (9891145409) 5


Q A text file contains alphanumeric text(say demo.txt). Write a program that read thistext file
and print only the numbers from the file.
def Execute():
f=open("demo.txt",'r')
for i in f:
for j in i:
if j.isdigit():
print(j, end=' ')f.close()
Execute()

Q-Define a function execute() that will read a text file demo.txt. This function will printjust the last line of this
text file.

def Execute(): f=open("demo.txt",'r')


k=f.readlines()
print(k[-1])
f.close()
Execute()

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()

AMIT KUMAR KUSHWAHA (9891145409) 6


seek(): to change the position of file handle by placing the file pointer at the specified position
in the open file
• f.seek(offset,mode)
• Where offset is a number specifying bytes
• Mode is 0 (beginning ) , 1( current
position ) 2(end of file)
• Default mode is 0 i.e. beginning
For example if f=open(‘marks.dat’,’r’)
f.seek(30) // will place your pointer to 30 bytes from beginning
f.seek(30,1) // will place your pointer to 30 bytes in forward direction from current position
f.seek(-30,1) // will place your pointer to 30 bytes in backward from current position
f.seek(-30,2) // will place your pointer to 30 bytes in behind from end of file from beginning

tell(): returns the current position of a file pos= f.tell()

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')

AMIT KUMAR KUSHWAHA (9891145409) 7


Mno=int(input("enter Member number"))
Mname = input("Member Name")
Type=input("Member type(S/L) ")
rec = [Mno,Mname,Type]
pickle.dump(rec,f)
f.close()
def Display():
rec=[]
f = open("club.dat","rb")
try :
while True:
rec = pickle.load(f)
print(" Member Number",rec[0])
print(" member Name ",rec[1])
print(" member type ",rec[2])
except EOFError:
print("File end")
break
f.close()
def Update():
rec=[ ]
a=int(input('Enter Member number to update'))
f=open("club.dat",'rb+')
found =False
try :
while True :
rpos=f.tell()
rec=pickle.load(f)
if rec['Mno']==a:
rec['Mno']+= 1
f.seek(rpos)
pickle.dump(rec,f)
found = True
except EOFError:
if found==False:
print("sorry record not found")
else:
print("Record updated")
f.close()
ans=0
res='y'
print("Menu")
print("1.Add record")
print("2.Display")
print("3.update")
print("4. exit")
while res=='y':
ans =int(input("Enter your choice"))
if ans==1:
ADD()
elif ans==2:
Display()
elif ans==3:
Update()
AMIT KUMAR KUSHWAHA (9891145409) 8
elif ans==4:
exit()
res = input("Do you want to contine")
Q- A binary file PRODUCT.DAT (a pickled file ) stores the record having the following structure
[<Pcode>, <Pname>, <Qty>,<Cost>]
Write a program in python that defines and call the following user defined function
d) WAF named Create() to input data for Product records and add to pickled file PRODUCT.DAT
e) WAF Search() in python which prints the records having a specific code in the file
“PRODUCT.DAT”. Input the Product code to be searched. If no matching record is found, it
displays a message about it.
Code :
import pickle
def Create():
F=open(“PRODUCT.DAT”,’ab’)
Prod = [ ]
ans=’y’
while ans=’y’:
Pcode = int(input(“Enter product code ”))
Pname = input(“Enter product name ”)
Qty = int(input(“Enter product Quantity ”))
Cost = int(input(“Enter product cost ”))
Prod= [Pcode, Pname, Qty,Cost]
pickle.dump(Prod,F)
ans=input(“Do you want to continue”)
if ans!=’y’:
break
F.close()
def search():
P_Code=input(“Enter product code to be search”)
Prod=[ ]
Found = False
with open(“PRODUCT.DAT”,’rb’) as F:
Prod = pickle.load(F)
For rec in Prod:
if rec[0]=P_Code :
print(Rec)
Found = True
if found = False:
print(“Record not found”)

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

AMIT KUMAR KUSHWAHA (9891145409) 9


Role of argument Newline while opening file – it is an optional concept but very important because while
writing data in CSV files an additional EOL translation take place which insert an additional line between
each record so newline argument use used to suppress that EOL character

For example : f=open(“student.csv”,’w’,newline=” ”)

Writing into CSV file


 csv.writer() - return a writer object which writes data into CSV file
 writerobject.writerow() - write one rwo of data onto writer object
 writerobject.writerows() - write multiple rows of data onto writer object

Reading from CSV file : csv. reader()-read whole file at a time

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()

AMIT KUMAR KUSHWAHA (9891145409) 10

You might also like