Professional Documents
Culture Documents
File Handling Cs Class 12
File Handling Cs Class 12
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.
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>)
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”)
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.
PRACTICAL: 1
To open a file XII.txt type the following command:
>>> CPS = open(“XII.txt”,”w”)
>>>print(CPS)
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.
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.
4
File1 = open(“D:\\Class\\XII.txt”)
Readinfo = File1.read(15)
print(Readinfo)
OUTPUT
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
Use end = ‘ ‘ argument in the end of print( ) statement to get the output in the
exact form stored in the file.
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
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 Functions
1. Function Name write( )
Syntax <filehandle>.write(str1)
Description writes string str1 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.
OUTPUT
11
Including the following in the above program code will display the names in next line.
fileout.write(“\n”)
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
For example
fileout= open("D:\\Marks.txt","r")
show1 = fileout.read(3)
15
print(show1)
show2 = fileout.read(3)
print(show2)
fileout.close()
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.
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
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.
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
Object/Variable Function
19