Chapter 4 File Handlinf Final (New)
Chapter 4 File Handlinf Final (New)
2020
Presented By :
MR. M. GOVINDA RAO
PGT(Comp. Sc. )
DAV PUBLIC SCHOOL BERHAMPUR
Bhubaneswar Region, Odisha , Zone-1
Learning objective
Why need File Handling
Types of File
Program in RAM
TYPES OF FILES
File are of Three types –
1. Text File: A Text file stores information in ASCII or Unicode characters
(The
one which we can understand very easily).In text file each line is
terminated
with a special character known as EOL(End of Line).In Python, by default,
this EOL character is the newline character(„\n‟) or carriage-return, newline
combination („\r\n‟).
2. Binary File: A binary file is just a file that contains information in the same
format in which the information is held in memory i.e the file content that is
returned to you is raw (with no translation or no specific coding. It is used
to store binary data such as images, videos audio etc.Generally numbers
are stored in binary files. In binary file,there is no delimiter to end a line.
Since they are directly in the form of binary hence there is no need to
translate them.That’s why these files are easy and fast in working.
3. The CSV is a file, it stands for Comma separated values , it is a simple file
format used to store tabular data, such as spreadsheet or database. In which each
line is a record. The record consist of fields separated by comma. it can be
Notepad file, in which each row data should be separated by comma., When you
will open in Notepad it will display normal text separated by comma. It can be
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES
Text Files Binary Files
1.Text Files are sequential files 1. A Binary file contain arbitrary
binary data
2. Text files only stores texts 2. Binary Files are used to store
binary data such as image, video,
audio, text
3. There is a delimiter EOL 3. There is no delimiter
(End of Line i.e \n)
2. Opening a file
5. Closing a file
Operation on File Handling
Whenever we worked with Data file
in Python we have to follow sequence
Open/Create file
Read from/ write to file
Close file
We can do following tasks/
operation with python data files.
Creation/opening of an existing data file.
Reading from file.
Writing to data file.
Appending data(inserting data at the end
of the file)
Inserting data(in between the file)
Deleting data from file
copying a file
Modification/ updation in data file
Python File Handling System
Text files in Python
Text file don’t have any specific encoding and
it can be opened in normal text editor itself.
Example :-
Web Standards : html, XML, Css, JsON etc.
Source Code : C, app, JS, py, Java, etc.
Documents : txt, tex, RTF etc.
Tabular Data : CSV, tsv, etc.
Configuration : ini, ctg, reg etc.
TWO METHODS TO
OPENING A TEXT FILES
Using open()
function
External File
Using with
(Secodry
Storage)
statement
OPENING A FILES USING OPEN()
• We need a file variable or file handle to work with files in Python.
• This file object can be created by using open( ) function .
• Open( ) function creates a file object, which is used later to access
the file using the functions related to file manipulation.
• Its syntax is following –
<file_object> = open(<filename>) Example: f= open(“Hello.txt”)
OR Example: f=open(“Hello.txt”,”r”)
<file_object>=open(<file_name>,<access_mode>)
External File
File Handle Mode (Secodry
of
or Path to a file a file Storage)
File object created
File handler is also know as file object is like a cursor, which defines from where
the data has to be read or written in the file
Access modes govern the type of operations possible in the opened file
Example:
• F = open(“Hello.txt”)
• The above statement opens file Hello.txt as read mode (default mode) and attaches it to file
object named F
• F = open(“myfile.txt”,’r’)
The above statement opens Hello.txt in read mode (default mode) and attaches it to file
object named F
• F= open(“C:\\Users\\DELL\\Desktop\\Hello.txt”, “r”)
The above statement opens file Hello.txt in a specific folder in read mode (default mode) and
attaches it to file object named F.
However, if you want to write with a single slash you may write in raw string that means there
is no special meaning attached to any character. as follow :
r+ To Read and write but the file pointer will be at the beginning of the file.
w
Only writing mode, if file is existing the old file will be overwritten else the
new file will be created.
w+ Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exists , create a new file for reading and
writing.
a
Append mode. The file pointer will be at the end of the file.
a+
Appending and reading if the file is existing then file pointer will be at the
end of the file else new file will be created for reading and writing.
Closing A Files
• A close( ) function breaks the link of file-object and
the file on the disk.
• After close( ), no task can be performed on that file
through the file-object.
File
Object
Functions used Text File
S.NO Function Syntax Use
Name
01 open() F_obj=open(“File To open or create a file in desired
name”,”mode”) mode.
02 close() F_obj=close() To close the file.
Output
OPENING A FILES USING WITH STATEMENT
• This Method is very handy when you have two related operations
which you would like to execute as a pair, with a block of code in
between.
• Benefits of using with statement
It automatically closes the file after the nested block of code
It also handle all the exception also occurred before the end of
block.
• Its syntax is following –
with open(<filename>,< File Mode>) as <File Handle>:
For Example: External File
(Secodry
with open(“Poem.txt”,”w”) as f: Storage)
f.write( “Twinkle twinkle little star,\n”)
f.write( “How I wonder what you are,\n”)
f.write( “Up abobe the world so high,\n”)
f.write( “Like a dimond in the sky,\n”)
Reading Data from a file
We can read characters into file
by using following three method.
PYTHON
read( ) PROGRAM
readline()
readlines( )
A Program read into a text file from hard disk.
read()
Reads at most n bytes;
if no n is not specified,reads the entire file.
Returns the read bytes in the form of a string.
Syntax:<Filehandle>.read([n])
Example :-
A Program to read
“Hello.txt” File
Reading First 10
character from the
“Hello.txt” File
readline()
Reads a line of input ; if n is specified reads at
most n bytes.
Returns the read bytes in the form of a string
ending with ‘\n’ character.
Returns a blank string if no more bytes are left
for reading in the file.
Syntax : <Filehandle>.readline()
For Example:-
Which can read one line
at a time from the file.
readlines()
Reads all the lines of a text file.
Returns in the form of list.
Syntax : <FileHandle>.readlines()
For Example :-
It is used to
read many
lines.
Lets Demonstrate
Read() Operation
Readline() Operation
Readlines() Operation
QUIZ TIME
Q-4. Which of the following are the attributes related to a file object?
A. closed
B. mode
C. name
D. rename
QUIZ TIME
Q-4. Which of the following are the attributes related to a file object?
A. closed
B. mode
C. name
D. rename
QUIZ TIME
Which of the following are the attributes related to a file object?
A. closed
B. mode
C. name
D. rename
How to write data in a file?
• We can write characters into file by
using following two method.
PYTHON
write (string) PROGRAM
Output
writelines(sequence of lines)
writelines( ) method is used to write sequence
data types in a file (string, list and tuple etc.)
A Program to write
in “Demo.txt”
Output
Appending data to a File
Append means to add the data at the end of file using ‘a’ mode.
A Program to
If file doesn’t exists, it will create the new file. write in
If file exists, it will append the data at the end of a file. “Hello1.txt”
• A
Output
Output
rb+ To Read and write binary file. But the file pointer will be at the
beginning of the file.
wb Binary file only in writing mode, if file is existing the old file will be
overwritten else the new file will be created.
wb+ Binary file only in reading and writing mode, if file is existing the old file
will be overwritten else the new file will be created.
ab Append mode in binary file. The file pointer will be at the end of the file.
Appending and reading in binary file if the file is existing then file
ab+
pointer will be at the end of the file else new file will be created for
reading and writing.
Opening & Closing a Binary file
Open() function is used to open a binary file same as text file. The
only difference is the mode which it is opened.
For Exp. F= open (“Binaryfile. dat”,”rb”)
A part from using open() function for creation of file , with
statement can also be used.
For Exp. With open(“ Binary.dat”,”r+”) as f
Closing Binary file : After performing desired operations on file,
we need to close it. This can be done same as text file using
close() function.
For Exp. F. close()
Important Note :-
In Python, files are opening in Text mode by default and so to open files in binary
mode , when specifying a mode, add ‘b‘ to it. For Example, read mode will
became ‘rb’, write mode will became ‘wb’ , append mode will became ‘ab’, and
read write will became ‘ab+’
BASIC OPERATIONS ON BINARY FILE
Basic operations performed on a Binary file are:
Write a record in a binary file
Important Note :-
• Pickle is a built – in module in Python.
• It is used write of read a structure such as list or dictionary to a file.
• First we need to import the Pickle module.
import pickle
Working of Pickling(dump())
• It writes the object to a
Structure (List /
file.
Dictionary)
Code • Syntax:
pickle.dump(object,FileObject)
• Object can be list,
Pickling dictionary or number.
• FileObject is the file
handler
Byte Output
Stream
m
le
e adab
R
Writing to Not
File
Working of Unpickling( load())
• As we know that binary files
are not in readable form Byte
• pickle.load() is used to read Stream
from binary file.
• Syntax:
object=pickle.load(FileObject)
• Object can be list, dictionary Unpickling
or number. Output
• FileObject is the file handler
Structure (List /
Code
Dictionary)
User Readable
seek method
tell method
seek() function is used to change the position of the file handle (file
pointer) to a given specific position. File pointer is like a cursor, which defines
from where the data has to be read or written in the file.
Syntax :
f.seek(offset, from_what)
where f is file pointer
seek(offset) : Change the cursor position by bytes as specified by the offset.
Offset is added to from_what (reference point) : To get the position.
seek() & tell() Methods
The reference point is defined by the "from_what"
argument. It can have any of the three values:
0: sets the reference point at the beginning of the file,
which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file.
Important Point :-
In Python 3.X and above we can Seek from beginning only, if
opened in text mode. We can overcome from this by opening the
file ion b mode.
tell() method returns an integer giving the current position of
object in the file. The integer returned specifies the number of bytes
from the beginning of the file till the current position of file object.
It's syntax is : fileobject.tell()
Examples on seek() & tell()
Output
HANDLING FILES THROUGH OS MODULE
OS module provides many such functions which can
be used to work with files and directories. OS means
Operating System.The os module of Python allows
you to perform Operating System dependent
operations such as making a folder, listing contents
of a folder, know about a process, end a process
rename a file , remove a file etc…
Let's see some useful os module methods that can
help you to handle files and folders in your program.
• First we need to import the os module.
METHODS OF OS MODULE
S.NO Function Syntax Use
Name
01 os.mkdir(“newdir”) To create directory in the current
mkdir() directory.
02 os.chdir(“newdir”) To change the current directory
chdir()
03 os.getcwd() It display the current directory
getcwd()
04 os.rmdir(“newdir”) To delete the directory
rmdir()
05 Os.rename(cur_file, It is used to rename the file.
rename() new_File)
06 os.remove(File_name) It is used to delete the file.
remove()
ABSOLTE PATH
RELATIVE PATH
A relative path, is a path starting from the Current Directory of your
program. The Current Directory is usually the directory containing the
file executed.
For Example :-
If my current working directory is c:\program, then to access .py, we
should write only append.py.
Programs\append.py
RELATIVE PATH
Standard Input, Output and Error Stream
• Standard Input Device(stdin)- reads from the keyboard
• Standard Output Device(stdout)- prints to the display and can
be redirected as standard input.
• Standard Error Device(stderr)- same as stdout but normally
only for errors.
• The above devices are implemented as files in Python , called
standard streams.
• We can use these stream files by using sys modules.
• Import sys module.
• sys.stdin.read() : let you read from keyboard.
• sys.stdout.write() : let you write on the standard output device, the
monitor.
• sys.stdin is the file for input, always opens in read mode.
• sys.stdout is the file for output , always opens in write mode
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
Output
– Standard error Stream
sys.stderr
Daily Quiz & MCQ
#Write a program to write and read multiple record in the form of list in a
Algoritham
Opens a binary file “Employee.dat” in
write mode and then write these list
to a binary file using dump
method,according to the user want.
The load method is used to read the
object from the binary file.
Note: The pickle.load() function
raises EOFError(a run time exception
error) when the end of file is reached
while reading from the file. This can
be handled either by using try and
except block
#Write a program to append and display multiple record in the form of
list
in a binary file according to the user choice To add more data
at the end of the
file the file is
opened in an
append mode.
Algoritham
Opens a binary file
“Employee.dat” in append
mode and then write these
list to a binary file using
dump method,according to
the user want. The load
method is used to read the
object from the binary file.
Note: The pickle.load()
function raises EOFError(a
run time exception error)
when the end of file is
reached while reading from
the file. This can be handled
either by using try and
except block
# W.A.P to Searching records according to the Emp_no
Algoritham
Step-1 open the file in binary in read mode
Step-2 Input the Emp_no whose data needs to be searched.
Step-3 Apply loop to read the file record by record from beginning till end.
Step-4 Read the record of the file in a list using load method
Step-5 If the Employee no. read from the file matches the Emo_no to be searched then print the
record and display the message “Found”.
Step-6 If the Employee number read from the file does not match the Emp_no to be searched
then the variable found remains false and "Record not found" is displayed.
Step-7 Close the file
Note:
The pickle.load()
function raises
EOFError(a run time
exception error)
when the end of file
is reached.
# W.A.P to updating the salary you want in Multiple records
Algoritham
Step-1 opening the file in both
reading and writing modes.
Step 2 Input the Employee No. whose
data needs to be modified.
Strp-3 Apply loop to read the file
record by record from
beginning till end.
Step-4 Store the position of file
pointer of the beginning of
the record
Step-5 Read the record of the file in a
list
Step- 6 Asdk the user to enter the
modified salary
Step-7 Overwrite the earlier record
with new record
Step8 Write the modified record
back to the file
Step-9 If the Employee number read
from the file does not match
the Emp_no to be searched
then the variable found
remains false and "Record
not found" is displayed
Step-10 Close the file
#WAP to delete data in Binary file
import pickle
import os
def delete_rec():
f=open("Student.dat","rb")
f1=open("Temp.dat","wb")
a=int(input(" Enter the Roll no to be deleted"))
found=0
try:
while True:
R=pickle.load(f)
if R[0]==a:
found+=1
else:
pickle.dump(R,f1)
except EOFError:
f.close()
f1.close()
if found==0:
print("Record not found")
os.remove("Student.dat")
os.rename("Temp.dat","Student.dat")
delete_rec():
Practical Questions
which can be asked
in the Board
Examination.
(Binary file)
Expected Board Questions Binary file ( 3Marks)
Q1. Write a function definition to search and display all those records of
the student whose percentage is between 70 and 90 (Both inclusive)
Assuming that the data is stored in the Binary file in the following
format:
[[1,’Ram’, ‘A’, 75], [2,’Allen’, ‘B’, 75], [2,’Neha’, ‘C’, 75],……..] and so on
Q3. Write a function defination to transfer all the records from binary file
“Pro” to “Newpro” whose price is less than 1000.
Output
How to Search data from a csv file
Output
Practical Questions
which can be asked
in the Board
Examination.
(CSV File)
Expected Board Questions CSV file ( 3Marks)
Q1. Write a user define function search() to display those
percentage are in the range of 80 and 90 (both values
included)
Q2. Write a python script to create a file Camera.CSV having
fields ModelNO,Megapixel, Zoom and details using tab as a
delimiter.
Q3. Write a python script to read a Voter.CSV file having fields
Voter_ID,VoterName,VoterAge.Display those records where
voter age is more than 65.
Q4. Write a python script to read a Student.CSV file having
fields RollNo,Eng,Science,Math,SST marks. Calculate total and
pecentage. Display Rollno,total and percentage of all students.
Q5.Write a Python script to read a PHONE.CSV file containing
Name, Address, Areacode and phone no. Display all records in
ascending order.