Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

CENTRAL PUBLIC SR. SEC.

SCHOOL
TARGET CBSE BOARD EXAMINATION 2021 – 2022
SUBJECT COMPUTER SCIENCE (083 - NEW)

CHAPTER – 5
FILE HANDLING
CBSE Syllabus
• Introduction to files, types of files (Text file, Binary file, CSV file), relative and
absolute paths
• Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a
text file, opening a file using with clause, writing/appending data to a text file
using write() and writelines(), reading from a text file using read(), readline()
and readlines(), seek and tell methods, manipulation of data in a text file
• Binary file: basic operations on a binary file: open using file open modes (rb,
rb+, wb, wb+, ab, ab+), close a binary file, import pickle module, dump() and
load() method, read, write/create, search, append and update operations in a
binary file
• CSV file: import csv module, open / close csv file, write into a csv file using
csv.writerow() and read from a csv file using csv.reader( )

What is a file?
A file in itself is a bunch of bytes stored on some storage device like hard-disk,
thumb-drive etc.

DATE FILES
Data filesare the files that store data pertaining to a specific application, for later use.
The data files can be stored in two ways :
1. Text files
2. Binary Files

1. Text Files:
a. It stores information in ASCII or Unicode characters.
b. In text file, each line of text is terminated with a special character known as
EOL (End Of Line).
c. In Python by default this EOL character is the newline character (‘\n’)

1
2. Binary Files:
a. This file contains information in the same format in which the information is
held in memory.
b. In binary file, there is no delimiter for a line.
c. No translations occur in binary file.
d. These files are faster and easier for a program to read and write.
e. These files are the best way to store program information.

OPENING AND CLOSING FILES


To work with files in Python program, we need to open it in a specific mode as per
the file manipulation task we want to perform. These tasks are adding, modifying or
deleting data in a file. The operations that take place in file handling are:
(a) Reading data from files
(b) Writing data from files
(c) Appending data from files

Python provides built in functions to perform these operations. These functions are:
OPENING FILES:
In data file handling through Python first we need to open the file. This can be done
using open( ) function by using following syntax:
<file_objectname> = open(<filename>)
<file_objectname> = open(<filename>, <mode>)

For example cps = open(“XII.txt”) //Python will search this file.

 Read mode is the default mode in which every file opens and in the above
example the file XII.txt will be open in read mode.
This command can be written in this form also
For example cps = open(“XII.txt”, “r”)

This command can be written in this form also


For example cps = open(“d:\\Class\XII.txt”, “r”) //Python will search this file in
D:\Class Folder

2
What is file object?
Python open( ) function creates a file object which serves as a link to a file residing on
your computer. It is a reference to a file on disk.

What is file-mode?
It is the second parameter of the open function which is read (‘r’), write (‘w’) or
append (‘a’)mode.

 So we have learn that a file open function has three parameters:


File Object = Path to file Mode

What will happen if the filename is given without its path?


If we just give the file name without its path Python will create the file in the same
directory in which the module file is stored.

PRACTICAL: 1
To open a file XII.txt type the following command:
>>> CPS = open(“XII.txt”,”w”)
>>>print(CPS)

The file XII.txt appears in the Python folder.

FILE ACCESS MODES


A file mode governs the type of operations (such as read, write or append) possible in
the opened file i.e. it refers to the file how it will be used. Following are the file
modes in Python:

3
Text File Mode Binary File Mode Description
‘r’ ‘rb’ Read only
‘w’ ‘wb’ Write only
‘a’ ‘ab’ Append
‘r+’ ‘r+b’ or ‘rb+’ Read and write
‘w+’ ‘w+b’ or ‘wb+’ Write and read
‘a+’ ‘a+b’ or ‘ab+’ Write and read
 Adding ‘b’ to text file mode makes it binary-file mode.

How to create a file?


To create a file, we need to open a file in write mode i.e. ‘w’ or ‘a’ or ‘w+’ or ‘a+’
modes.

CLOSING FILES
An open file is closed by calling the close( ) method of its file-object. Closing of file is
important. In Python files are automatically closed at the end of the program. The
operating system may not write the data out to the file until it is closed. So it is
important to close the file. Syntax to close a file is as follows:
<fileHandle>.close( )
 Open( ) is a built in function while close( ) is a method used with file handle object.

READING AND WRITING FILES


Python provides many functions for reading and writing the open files.
Reading from Files
Python provides mainly three types of read functions to read from a data file.
1. Function Name read( )
Syntax <filehandle>.read([n])
Description Reads at most n bytes; if no n is specified, reads the entire
file.
For example
Just create a Folder with name Class in D:
Now create a file with name XII.txt (Notepad File) in Folder
Now type the following lines in that Notepad File
We are learning chapter number 5 of class XII CS. It is
related to File Handling where we can store our data for
future reference.
Now type the following python program:

4
File1 = open(“D:\\Class\\XII.txt”)
Readinfo = File1.read(15)
print(Readinfo)

OUTPUT

2. Function Name readline( )


Syntax <filehandle>.readline([n])
Description Reads a line of input; if n is specified reads at most n bytes.
For example:
File1 = open(“D:\\Class\\XII.txt”)
Readinfo = File1.readline( )
print(readinfo)

OUTPUT

3. Function Name readlines( )


Syntax <filehandle>.readlines( )
Description Reads all lines and returns them in a list.
For example:
File1 = open(“D:\\Class\\XII.txt”)
Readinfo = File1.readlines( )
print(readinfo)
5
OUTPUT

 When we specify number of bytes with read( ), Python will read only the specified
number of bytes from the file.
 The next read( ) function start reading from the last position read.
For example:
File1 = open(“D:\\Class\\XII.txt”)
Readinfo = File1.read(15)
print(Readinfo)
Readinginfo = File1.read(10)
print(Readinginfo)

OUTPUT

* A single task can also be performed by combining the two steps


of opening the file and performing the task. For example:
>>>File1 = open(“D:\\Class\\XII.txt”,’r’).readline( )
6
>>>print(File1)
OR
>>>File1 = open(“D:\\Class\\XII.txt”,’r’).read(30)
>>>print(File1)
OR
>>>File1 = open(“D:\\Class\\XII.txt”,’r’).readlines( )
>>>print(File1)

 Use end = ‘ ‘ argument in the end of print( ) statement to get the output in the
exact form stored in the file.

Now add few lines in your text file.


For example:
We are learning chapter number 5 of class XII CS.
It is related to File Handling where we can store our data for future reference.
Filesare stored in storage devices like hard disk, memory card, flash drive etc.
These files are of two types Text Files and Binary Files.
Once files is stored then various operations like reading, writing and append can be
done easily.

Now with the help of above example we will try to read first three lines of our text
file.
File1 = open(“D:\\Class\\XII.txt”, ‘r’)
Readinfo = File1.readline( )
print(Readinfo, end = ’ ‘)
Readinfo = File1.readline( )
print(Readinfo, end = ’ ‘)
Readinfo = File1.readline( )
print(Readinfo, end = ’ ‘)
File1.close( )

7
OUTPUT

Reading a complete file line by line.


File1 = open(“D:\\Class\\XII.txt”, ‘r’)
Readinfo = “ “
whileReadinfo :
Readinfo = File1.readline( )
print(Readinfo, end = ’ ‘)
File1.close( )

OUTPUT

OR
8
You can use the following command lines also to print any file line by line.
File1 = open("D:\\Class\\XII.txt", 'r')
for line in File1 :
print(line)

 The readline( ) function reads the leading and trailing spaces along with newline
character(‘\n”) while reading the lines.
 We can remove the leading and trailing spaces (spaces, tabs and newlines) using
strip( ) function.

Program to display the size of a file after removing EOL characters, leading and
trailing white spaces and blank lines.
File1 = open(“D:\\Class\\XII.txt”, ‘r’)
Readinfo = “ “
size = 0
tsize = 0
whileReadinfo :
Readinfo = File1.readline( )
tsize = tsize + len(Readinfo)
size = size + len(Readinfo.strip( ))
print(“Size of file after removing all EOL characters and blank lines: “, size)
print(”The total size of the file: “, tsize)
File1.close( )

OUTPUT

9
Program to display the number of lines in the file.
File1 = open(“D:\\Class\\XII.txt”, ‘r’)
Readinfo = File1.readline( )
linecount = len(Readinfo)
print(“Number of lines in text file are = ”, linecount)
File1.close( )

OUTPUT

WRITING INTO FILES


Writing functions for data files available in Python using file-object or file-handle.
Python provides mainly two types of write functions to write in a data file.

Writing Functions
1. Function Name write( )
Syntax <filehandle>.write(str1)
Description writes string str1 to file referenced by <filehandle>

2. Function Name writelines( )


Syntax <filehandle>.writelines(L)
Description writes all string in list L as lines to file referenced by
<filehandle>

 When we open a file in “w” (write) mode, Python overwrites an existing file or
creates a non-existing file. It means it creates a file with same name and the
earlier data gets lost.

10
APPENDING A FILE
 If we want to retain the old data with the new existing one, we have to open
the file in “a” (append) mode.
 A file opened in append mode retains its previous data allowing us to add
newer data into it.
 We can add ‘+’ symbol with file read mode to facilitate reading as well as
writing.

Points to remember:
1. In an existing file, while retaining its contents:
(a) The file must be opened in append mode (“a”) to retain its old content.
(b) To facilitate reading as well as writing, the file should be opened in ‘r+’ or
‘a+’ modes.
2. To create a new file or to overwrite contents of a file
(a) The file must be opened in write (“w”) only mode
(b) If the file is opened in (“w+”) mode it facilitate for reading and writing.
3. It is very important to use close( ) on file-object to close a file.

Program to hold some data in a file.


fileout = open(D:\\”Student.txt”,”w”)
for I in range(5) :
name = input(“Enter name of student : “)
fileout.write(name)
fileout.close()

OUTPUT

11
Including the following in the above program code will display the names in next line.
fileout.write(“\n”)

Program to store data of students of a classincluding name, father’s_name, class,


roll_no, percentage in a file named Marks.txt.

count = int(input("Enter the number of students in the class : "))


fileout = open("D:\\Marks.txt","w")
for i in range(count):
print("Enter details of student ", (i+1), "below: ")
roll_no = int(input("Roll No. : "))
name = input("Name : ")
percentage = float(input("Percentage : "))
rec = str(roll_no) + "," + name+ ", " + str(percentage)+"\n"
fileout.write(rec)
fileout.close()

OUTPUT

12
Program to add two more databases of students in the above program code.
fileout = open("D:\\Marks.txt","a")
for i in range(2):
print("Enter details of student ", (i+1), "below: ")
roll_no = int(input("Roll No. : "))
name = input("Name : ")
percentage = float(input("Percentage : "))
rec = str(roll_no) + "," + name+ ", " + str(percentage)+"\n"
fileout.write(rec)
fileout.close()

OUTPUT

13
Program to display contents of a saved file.
fileinp = open("D:\\Marks.txt")
whilestr :
str = fileinp.readline()
print(str)
fileinp.close()

OUTPUT

THE FLUSH( ) FUNCTION


Whenever we use to write onto a file using write function, Python holds everything
to write in the file in buffer and pushes it onto actual file on storage device later. By
using flush( ) function we can force Python to write the contents of buffer to file.
Python automatically flushes the files when closing the program which is called by
close( ) function. But we must flush the data before closing any file. Syntax to use
flush( ) function
14
<fileobject>.flush
For example:
fileinp.flush( )
fileinp.close( )

REMOVING WHITESPACES AFTER READING FROM FILE:


To remove whitespaces we use strip( ) function, rstrip( ) and lstrip( ) function.
strip( ) function removes the given character from both ends.
rstrip( ) function removes the character from the right end.
lstrip( ) function removes the character from the left end.

STEPS TO PROCESS A FILE


Step – 1 Determine the type of file usage
Firstly we have to determine that for which purpose the file is going to
be used. Different modes are used with open function. They are
“r” , “r+ “, “w” , “w+” or “a”
Step – 2 Open a file and assign its reference to a file-object or file-handle
It is important to assign reference to the file object on which all the file
operations will be performed.
Step – 3 Process as required
After creating / opening a file processing takes place which can be
performed as required.
Step – 4 Closing a file
A file must be closed as soon as the required operations get completed
related to the file. It is important because sometimes the data may loss
as it remains in buffer and not pushed into the file.

SIGNIFICANCE OF FILE POINTER IN FILE HANDLING


Every file maintains a file pointer which tells the current position in the file. It is just
like a bookmark in a book. Whenever we read something from the file or write
something onto a file two things happen related to file pointer:
1. This operation takes place at the position of file pointer and
2. File-pointer advances by the specified number of bytes.

For example
fileout= open("D:\\Marks.txt","r")
show1 = fileout.read(3)
15
print(show1)
show2 = fileout.read(3)
print(show2)
fileout.close()

FILE MODES AND OPENING POSITION OF FILE POINTER


The position of a file pointer is governed by the filemode it is opened in. The
following table shows the opening position of a file-pointer as per filemodes:

File Modes Opening position of file-pointer


r, rb, r+, rb+, r+b Beginning of the file
w, wb, w+, wb+, w+b Beginning of the file (Overwrites the file if the file exists)
a, ab, a+, ab+, a+b At the end of the file if the file exists otherwise creates a
new file.

STANDARD INPUT, OUTPUT AND ERROR STREAMS


Standard input device (stdin) – It reads from the keyboard.
Standard output device (stdout) – It displays output on monitor screen.
Standard error device (stderr) – It is same as stdout normally used for errors.

These standard devices are implemented as files called standard streams. In Python
we can use these standard streams by using sys module. After importing we can use
these streams (stdin, stdout and stderr) as other files.

STANDARD INPUT, STANDARD OUTPUT DEVICES AS FILES


When we import sys module in our program then, sys.stdin.read( ) would let you
read from keyboard. It’s because keyboard is the standard input device. In the same
way sys.stdout.write( ) would let you write on the standard output device monitor.
So we can say that sys.stdin and sys.stdout are standard input and standard output
devices respectively treated as files. These files are opened by the Python when we
start Python.
Remember the sys.stdin is always opened in read mode and sys.stdout is always
opened in write mode. Let’s have an example of it.

16
import sys
fh = open(“D:\\Marks.txt”)
line1 = fh.readline( )
line2 = fh.readline( )
sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stderr.write(“No errors occurred”)

OUTPUT

WITH STATEMENT OF PYTHON DATA FILES


The with statement of Python execute as a pair, with a block of code in between.
Syntax:
with open(<filename>, <filemode>) as <filehandle>:
<file manipulation satetements>

For example:
with open(‘Marks.txt’, ‘w’) as f:
f.write(‘Hi there!’)

17
The advantage of with statement is that it automatically close the file no matter how
the block exists.

ABSOLUTE PATH AND RELATIVE PATH


Every file, folder or directory consists of a path which shows that where it is located.
It is just a sequence of directory/folder names from where you can access it.
Syntax:
Complete path\filename.extension
OR
Drive-letter:\directory\folder…
The absolute pathare from the topmost level i.e. from the root directory.
The relative path are relative to current directory denoted as a dot(.) while its parent
directory is

Points to remember:
1. Data get lost if we not use File Handling because data stores in primary memory at
the time of running the program. To store data permanently we have to use file
handling.
2. A file is collection of characters where we can read, write or append the data.
3. File is a storage place where you can store data permanently.
4. To store data we use storage device like hard disk, flash drive, memory card etc.
5. Data can be stored in two forms : Text File and Binary Files
6. Operations which can be performed on files are : Read, Write and Append
18
7. A file is first opened / created then processing takes place and at last file must be
closed.
8. File operations which can be performed are insertion of data, deletion of data,
updating of data, displaying of data etc.
9. A file can be opened with the help of open() function with one variable also called
filehandle or file object.
10. So whatever command or operation performed on that variable means it is
performed on that file.
11.A file must be always opened in any of the following modes: ‘r’, ‘w’ or ‘a’.
12. In the same way a file must be always closed using close() function with
filehandle.
13. To open a file

Filehandle = open (“Path” , ’mode’)

Object/Variable Function

19

You might also like