You are on page 1of 14

L-5 File handling

File:-A file is bunch of bytes stored in storage


device.
Data files :-There are two types of data file:
i)Text file: It can be further divided into two types:
a)Regular Text file:It stores information in the same
form as you typed. Extension Name: .txt
b)Delimited Text File:-Specific characters is stored
to separate the value. Example .csv
(comma separated value).
ii) Binary file:-It stores information in the same format
in which information is stored in memory.
Steps for file operation:-
i)Opening a file ii)process the file iii) close the
file.
Opening a file:
Syntax: file object=open(“filename”, “file mode”)
Eg: To open a file “Student.dat” in read mode
F=open(“student.dat”,”r”) [ here F is file object]
Closing a file: syntax: file object.close()
Eg: F.close()
Writing to file: 1. Write( string)
Write(string): It writes string to the file.
Syntax: fileobject.write(“filename.txt”,”filemode”)
Practical1: use of write() function.
Eg: f=open(“abc.txt”,”w”)
f.write(“I love my country”)
f.close()
“w”-----write mode
“a”-------append mode
“r”---------read mode

Practical 2:Write numeric data in a text file “abc.txt”


Sol: f=open(“abc.txt”,”w”)
f.write(“try again”)
x=23
f.write(str(x))
f.close()
Note: str(numeric ):
Writelines(): It is use to write list, tuple and dictionary
in a file.

Sol: L=[1,3,5,7,9,11]
F1=open(“stud1.txt”,”w”)
F1.writelines(str(L))
F1.close()
With statement: It ensures that all resources allocated
to the file objects get de-allocated automatically. No
need to use close() function.
Syntax:
#Program to use “with” statements
Sol: with open(“abc.txt”,”w”) as f:
f.write(“India is my country”)
*Standard INPUT ,OUTPUT and ERROR streams:-
>>>import sys
Standard input device:-stdin
Standard output device:-stdout
Standard error device:-stderr

It prints the contents of a file without using print statement


Practical: print contents of a text file “abc.txt” without using
Print statement.
import sys
F1 =open(“abc.txt”,”r”)
L1=F1.readline()
Sys.stdout.write(L1)

Reading from a file


i)read(): It is use to read entire data from the file.
ii)read(n):-It reads n(size) characters from the file.
iii)readline():-It reads a line of input.
iv)readlines():- It reads all lines and return them in a list.
practical1: Reading entire data from a file abc.txt.(Use:read())
practical2:Reading specified bytes(data) from a text file
abc.txt(read(n))
Practical3: Practical based on readline() and readlines()
function.
Q.WAP to read a single line from the text file “abc.txt”.[use
readline()
HW:
i)write “Welcome to python” in a text file “pqr.txt”.
ii)Read entire contents of a file “pqr.txt”.
iii)Read only 4 bytes from a file “pqr.txt” and display it.
iv)WAP to write three lines in a text file “xyz.txt”.
v) WAP to read two lines separately from text file “xyz.txt”
hint: use readline()
vi) WAP to read entire line using readlines.
Q.what are the advantages of saving data in i)binary form ii)text
form.
Q what are two types of text files?-----i)Regular text file
ii)Delimited text file
Q Differentiate b/w i)”r” and “r+” ii)”r and “rb file
modesiii)”r+” and “w+” file mode. iii)”w” mode and “a”
modes.
Q. Write output:-
i)out=open(“output.txt”,”w”)
out.write(“Hello,world!\n”)
out.write(“How are you?”)
out.close()
a=open(“output.txt”).read()
print(a)
ans: output:
‘Hello,world!
How are you?’
ii) fh=open(“poem.txt”,”r”)
size=len(fh.read())
print(fh.read(5))
Ans:-No output.
iii)f1=open(“main.txt”,”w”) Imp
f1.write(“Bye”)
f1.close()
if the file contain “GOOD” before execution. What will be the
contents of the file.
Ans:-Contents of file will be only “Bye” when existing file is
opened in write mode(“w”),it truncates the existing data
“GOOD”.
Q. WAP to count total alphabets in a text file “abc.txt”.
Q.WAF to count total digits in a text file “abc.txt”
Q. Write a method in python to read lines from a text file
“abc.txt” to find and display the occurrence of the word
“the”.

Q. Write a function that counts the number of “Me” or “My”


words present in a text file “story.txt”.If contents are as
follows:-
“My first book
Was me and
My family.”
Output function should be:
Count of Me/My in file:3
Q. Write AMcount() in python which should read each
character of a text file “STORY.TXT” should count and display
the occurrence of alphabets ‘A’ and ‘M’(including lower case
also).
Eg:Function display the output like:-
A or a: 4
M or m:2.
Q.Write a function in python to read the content from a text
file STORY.TXT line by line
a) display those line which start from a character “H”
b) Count total no. of lines which start from a character “H”
HW:-
Q. Write two different function in Python :-i)To count the
number of lines in a text file “ABC.TXT”. ii)To count total
number of lines started with an alphabet “A”.
Q. Write a function i) to count total digits in a file “abc.txt” ii)
To count total no words “the”. Iii) To count total number
vowels in a text file “abc.txt”
Q. Write a function DISPWORD() in python to read lines
from a text file “STORY.TXT” and display those words which
are less than 4 characters.
Working with BINARY FILES:-It is basically write list or
dictionary in a file in binary format. Pickle module is
use to store file in binary form.
Pickle module provides two methods:-i) dump ii)load
import pickle
Syntax:
pickle.dump(list/dictionary, fileobject)#writting to
binary file
pickle.load(fileobject)->reading data from binary file.
Practical1 :WAP to a binary file “EMP.DAT” and write
records of employee in the form of dictionary.
Sol:
import pickle
e1={'eno':1001,'ename':'Mohit','age':38,'esal':55000}
e2={'eno':1002,'ename':'Nitin','age':40,'esal':56000}
f1=open("emp.dat","wb")
pickle.dump(e1,f1)
pickle.dump(e2,f1)
print("two records written in the file")
f1.close()
Prac2:WAP to add records(dicitionary) employee as per
users choice in a binary file emp.dat.
Pract3:WAP to open the file Emp.dat and read its
contents.(Through try block) or Alternative method
Prac4:Programme for inserting /appending record in a
binary file “student.dat”(using list)
Prac5: WAP to read a record from the binary file
“student.dat” (Records are stored in the form of List)
Prac6: WAP to search a record from the binary file-
“student.dat”
Prac7:Programe to update the name of the student
from the binary file.
*Pract8:Write a menu driven program to perform basic
Operations(Add, Search, modify and delete)using
(dictionary/List).(HW –Project work)

Q:9 A binary file “Book.dat” has structure [BookNo,


Book_Name, Author, Price]
[CBSE SAMPLE PAPER 20-21]
i. Write a user defined function CreateFile() to input
data for a record and add to Book.dat.
ii. Write a function CountRec(Author) in Python
which accepts the Author name as parameter and
count and return number of books by the given
Author are stored in the binary file “Book.dat”
Q10. A binary file “STUDENT.DAT” has structure
(admission_number, Name, Percentage). Write a
function countrec() in Python that would read contents
of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also
display number of students scoring above 75%

seek() function: seek() function changes the position of


the file pointer by placing the file pointer at the specified
position.
Syntax: file object.seek(offset,mode)
Offset->number of bytes.
Mode-> 0=>beginning of the file
1=>for current position of the file.
2=>end of the file
Eg: F1=open(“name.txt”,”r”)
F1.seek(30)F1.seek(30,0) [will place the file pointer
30 bytes from beginning]
F1.seek(30,1)=> [will place the file pointer 30 bytes
from current position]
F1.seek(-5,1)=> [will place the file pointer 5 bytes
backward direction from current file position ]
F1.seek(-30,2)=> [will place the file pointer 30 bytes
backward direction from end of file position]
tell() function: It returns the current position of the file
pointer in the file.
Syntax: fileobject .tell()
Eg:F1.tell()-> it tells about current position of the file
pointer in a file “Name.txt” in terms of bytes.
Prac11. Program to read byte by byte from a file using
seek and tell.
Csv files: CSV stands for comma separated value.It stores
Tabular data.
import csv
Opening a csv file: f2=open(“stud.csv”,”w”)
Advantages:-
i)CSV is faster to handle.
ii)CSV is smaller in size
iii)CSV is readable and easy to edit.
iv)Import on to a spreadsheet or database.
Writer in the csv file:-
>>>import csv
i)csv.writer()-- Returns a writer object which writes
data into a csv files.
ii)writeobject.writerow()Returns one row of data onto
the writer object.
iii) writeobject.writerows()Returns multiple row of
data on the writerobject.
Q. WAP to create a csv file to store student
data(Rollno,name ,marks)
Reading from a csv file:
Steps:-i) open csv file in read mode ii) declare reader
object. Iii) Display record.

Q.WAP to read emp.csv file contents.


Q.WAP to search record for given employee.

You might also like