Chapter-5 File Handling
5.1 Introduction
A file in itself is a bunch of bytes stored on some storage device.
File helps us to store the data permanently, which can be retrieved for
future use.
5.2 Data Files
Text Files:
Stores information in ASCII or Unicode characters.
Each line of text is terminated with a special character known as EOL
(End of Line).
Extension of text files is .txt
Default mode of file
The text files can be of following types:
(i) Regular Text files- These files store the text in the same form as
we typed. Here the newline character ends a line and have a file
extension as .txt.
(ii) Delimited Text files- In these files, a specific character is stored to
separate the values, i.e. a tab or a comma after every value.
Binary Files:
Contains information in the same format in which the information is held
in memory.
There is no delimiter for a line.
No translation are required
More secure
Difference between Text files and Binary files
Text files Binary files
Text files stores information in ASCII Binary files are used to store binary data
characters such as images, audio, video and text
Each line of text is terminated with a There is no delimiter in Binary file
special character known as EOL (End of
Line)
Text files are easy to understand Binary files are difficult to understand
because these files are in human
readable form
Text files are slower than binary files Binary files are faster and easier for a
program to read and write than the text
files.
Text files are having extension .txt Binary files are having extension .dat
5.3 Opening and closing Files
FileObject = open(<filename>)
or
FileObject = open (<filename>, <mode>)
(File object created) (Path to a File) (Mode of a file)
Example:
f = open (“myfile.txt”, ‘r’)
f = open (“c:\\users\\gaurav\\desktop\\textfile.txt”, “r”)
f = open (r “c:\users\gaurav\desktop\textfile.txt”, “r”)
A file-object is also known as file-handle. The file object is
used to read and write data to a file on disk. It is used to
obtain a reference to the file on disk and open it for a
number of different tasks.
When you open a file in read mode, the given file must exist
in the folder, otherwise Python will raise
FileNotFoundError.
The prefix r in front of a string makes it raw string that
means there is no special meaning attached to any
character.
The default file-open mode is read mode, i.e., if you do not
provide any file open mode, Python will open it in read
mode (“r”)
Closing files:- An open file is closed by calling the close() method of
its file-object. A close() function breaks the link of file-object and the file
on the disk. After close(), no tasks can be performed on that file through
the file-object (or file-handle)
Syntax:- <fileHandle>.close()
File Modes:
r To read the file this already exists.
rb Read Only in binary format.
r+ To Read and write but the file pointer will be at the beginning of the
file.
rb+ To Read and write binary file. But the file pointer will be at the
beginning of the file.
w Only writing mode, if file exists the old file will be overwritten else
the new file will be created.
wb Binary file only in writing mode, if file is exists the old file will be
overwritten else the new file will be created.
w+ Binary file only in reading and writing mode, if file is exists the old
file will be overwritten else the new file will be created.
a Append mode. The file pointer will be at the end of the file.
ab Append mode in binary file. 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.
ab+ Appending and reading in binary file 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
5.4 Working with Text Files
Reading data from a file:
read()
readline()
readlines()
read()- Reads at most n bytes; if no n is specified, reads the entire file.
Returns the read bytes in the form of a string.
Syntax: <Filehandle>.read([n])
readline()- reads one line at a time from the file.
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()
readlines()- Reads all the lines of a text file.
Returns in the form of list.
Syntax: <FileHandle>.readlines()
Program 1- Reading a file’s first 10 bytes and printing it.
f = open(r “E:\Gaurav\file.txt”, “r”)
str = f.read(10)
print(str)
Program 2- Reading a file’s entire contents
f = open(r “E:\Gaurav\file.txt”, “r”)
str = f.read()
print(str)
f.close()
Program 3- Reading the complete file in a list
f = open(r “E:\Gaurav\file.txt”, “r”)
str = f.readlines()
print(str)
f.close()
Note – The readlines() has read the entire file in a list of strings where
each line is stored as one string.
Program 4- Reading a complete file line by line
f = open('file1.txt', 'r')
str= " "
while str:
str = f.readline()
print(str)
f.close()
Program 5- Write a program to display the size of a file in bytes.
f = open('file1.txt', 'r')
str = f.read()
size = len(str)
print(“Number of lines in file.txt is”)
print(size, “bytes”)
Program 6- Write a program to display the number of lines in the file.
f = open(r 'd:\Gaurav\file1.txt', 'r')
str = f.readlines()
linecount = len(str)
print(“Number of lines in file1.txt is”, linecount)
f.close()
Writing data in a file
If file doesn’t exists, it will create the new file.
If file exists, it will write the data in the file.
write(string) –
write() method takes string and writes it in the file.
For storing data, with EOL character, we have to add ‘\n’ character
to the end of the string.
For storing numeric value, we have to either convert it into string
using str() or write in quotes.
writelines(string) – If we want to write list, tuple into the file then use it.
Appending data to a file
Append means to add the data at the end of file using ‘a’ mode.
If file does not exist, it will create the new file.
If file exists, it will append the data at the end of a file.
Program 7- Create a file to hold some data, separated as lines.
f = open(r 'd:\Gaurav\file1.txt', 'w')
for i in range (5):
name = input(“Enter name of student: ”)
f.write (name)
f.write(‘\n’)
f.close()
Program 8 – Creating a file with some names separated by newlines
characters without using write() function
f = open(r ‘d:\Gaurav\file2.txt’, ‘w’)
List1 = []
for i in range (5):
name = input(“Enter name of student: ”)
List1.append(name + ‘\n’)
f.writelines(List1)
f.close()
Program 9 – Write a program to get roll numbers, names and marks of the
students of a class (get from user) and store these details in a file called
“Marks.det”
count = int(input(“How many students are there in the class? ”))
f = open(r 'd:\Gaurav\Marks.det', 'w')
for i in range (count):
print(“Enter details for student”, (i+1), “below:” )
rollno = int(input(“RollNo: ”))
name = input(“Name: ”)
marks = float(input(“Marks: ”))
rec = str(rollno) + “,” + name + “,” + str(marks) + ‘\n’
f.write(rec)
f.close()
Program 10 – Write a program to display the contents of file “Marks.det”
created through program 9.
f = open(r 'd:\Gaurav\Marks.det', 'r')
while str:
str = f.readline()
print(str)
f.close()
flush() function – The flush() function forces the writing of data on
disc still pending in output buffer.
Syntax : <fileObject>.flush()
Reading whitespace after reading from file – read functions
also read the leading and trailing whitespaces i.e., spaces or tabs or
newline characters. If you want to remove any of these trailing and
leading whitespaces, you can use strip() functions [rstrip(), lstrip() and
strip()] as follows:
lstrip() – This method is used to remove the space which are at
left side of the string. Syntax- string.lstrip()
Example –
name = “ Gaurav”
str1 = name.lstrip()
print(name)
print(str1)
rstrip() – This method is used to remove the space which are at
right side of the string. Syntax- string.rstrip()
Example –
name = “Gaurav ”
str1 = name.rstrip()
print(name)
print(str1)
strip() – This method is used to remove the space from the both
side of the string. Syntax- string.strip()
Example –
name = “ Gaurav ”
str1 = name.strip()
print(name)
print(str1)
Standard Input, output and error streams –
standard input device (stdin) – read from the keyboard
standard output device (stdout) – display on the screen
standard error device (stderr) – same as stdout, but normally used
for errors only, displayed in red color
These standard devices are implemented as files called standard
streams.
sys module is to be imported to use these streams.
sys.stdin.read()
sys.stdout.write()
sys.stderr.write()
Example -
import sys
sys.stdout.write(“Enter first number:”)
a = int(sys.stdin.readline())
sys.stdout.write(“Enter second number:”)
b = int(sys.stdin.readline())
if b == 0:
sys.stderr.write(“Can’t divide any number by zero..”)
else:
sys.stdout.write(“Division Possible..”)
Using with statement – This method is very handy when you have
two related operation which you would like to execute as a pair, with a
block of code in between.
Syntax :
with open (<FileName>, <FileMode>) as <File Handle>:
f.write(“………….”)
Benefits of using with statement –
It automatically closes the file after the nested block of code.
It also handles all the exceptions also occurred before the end of
block.
#Two methods to open a File …………….
# Method 1 (using open() function)
f = open(“Myfile.txt”,”w”)
f.write(“Welcome to my tutorial of Python Programming….”)
f.close()
print(“Data written in a file…..”)
#Method 2 (using with statement…….)
with open(“Myfile1.txt”,”w”) as f:
f.write(“Welcome to my tutorial of Python Programming….”)
print(“Data written in a file…..”)
Accessing and Manipulating location of File – Random
Access
Python provides two functions that help us manipulate the position of file
pointer.
seek() – 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 : <file-object>.seek(offset, mode)
Where
Offset – is a number specifying number of bytes
Mode – is a number 0 or 1 or 2 signifying
0 - for beginning of file. It is a default position when no mode is
specified
1 - for current position of file-pointer
2 – for end of file
But in Python 3.x and above, we can seek from beginning only, if
opened in text mode. We can overcome from this by opening in b
mode.
tell() - The tell() function returns the current position of file pointer in
the file. Syntax:
<file-object>.tell()
Example 1 –
f = open(“Hello.txt”, “r”)
print(f.tell())
f.seek(3)
print(f.read())
f.seek(6)
print(f.read())
print(“Current location of pointer = ”,f.tell())
Example 2 –
f = open(“Hello.txt”, “rb”)
print(f.tell())
f.seek(3)
print(f.read(5))
print(“Current location of pointer = ”, f.tell())
f.seek(2, 1)
print(f.read(5))
print(“Current location of pointer = ”, f.tell())