Lecs 102
Lecs 102
C
File Handling
2 in Python
In this Chapter
» Introduction to Files
» Types of Files
» Opening and Closing a 2.1 INTRODUCTION TO FILES
Text File
We have so far created programs in Python that
» Writing to a Text File
accept the input, manipulate it and display the
» Reading from a Text File output. But that output is available only during
» Setting Offsets in a File execution of the program and input is to be
» Creating and Traversing a entered through the keyboard. This is because
Text File the variables used in a program have a lifetime
» The Pickle Module that lasts till the time the program is under
execution. What if we want to store the data that
were input as well as the generated output
permanently so that we can reuse it later?
Usually, organisations would want to
permanently store information about
employees, inventory, sales, etc. to avoid
repetitive tasks of entering the same data.
Hence, data are stored permanently on secondary
storage devices for reusability. We store Python
programs written in script mode with a .py
extension. Each program is stored on the
secondary device as a file. Likewise, the data
entered, and the output can be stored
2024-
25
permanently into a file.
2024-
25
So, what is a file? A file is a named location on a
secondary storage media where data are permanently
Text files contain stored for later access.
only the ASCII
equivalent of the
contents of the 2.2. TYPES OF FILES
file whereas a
Computers store every file as a collection of 0s and 1s
.docx file contains
many additional i.e., in binary form. Therefore, every file is basically
information like just a series of bytes stored one after the other. There
the author's name, are mainly two types of data files — text file and
page settings, font binary file. A text file consists of human readable
type and size, date characters, which can be opened by any text editor. On
of creation and
the other hand, binary files are made up of non-human
modification, etc.
readable characters and symbols, which require specific
programs to access its contents.
2.2.1 Text file
A text file can be understood as a sequence of characters
consisting of alphabets, numbers and other special
symbols. Files with extensions like .txt, .py, .csv, etc.
are some examples of text files. When we open a text file
using a text editor (e.g., Notepad), we see several lines
of text. However, the file contents are not stored in such
a way internally. Rather, they are stored in sequence
of bytes consisting of 0s and 1s. In ASCII, UNICODE or
Activity 2.1
any other encoding scheme, the value of each character
Create a text file using of the text file is stored as bytes. So, while opening a
notepad and write text file, the text editor translates each ASCII value
your name and save it.
Now, create a .docx file and shows us the equivalent character that is readable
using Microsoft Word by the human being. For example, the ASCII value 65
and write your name (binary equivalent 1000001) will be displayed by a text
and save it as well. editor as the letter ‘A’ since the number 65 in ASCII
Check and compare character set represents ‘A’.
the file size of both the
files. You will find that Each line of a text file is terminated by a special
the size of .txt file is character, called the End of Line (EOL). For example,
in bytes whereas the default EOL character in Python is the newline (\
that of .docx is in
KBs. n). However, other characters can be used to indicate
EOL. When a text editor or a program interpreter
encounters the ASCII equivalent of the EOL character,
it displays the remaining file contents starting from a
new line. Contents in a text file are usually separated
by whitespace, but comma (,) and tab (\t) are also
commonly used to separate values in a text file.
<a> Opens the file in append mode. If the file doesn’t exist, then End of the file
a new file will be created.
<a+> or <+a> Opens the file in append and read mode. If the file doesn’t End of the file
exist, then it will create a new file.
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements
of a list. However, if splitlines() is used instead of split(),
then each line is returned as element of a list, as shown
in the output below:
>>> for line in d:
words=line.splitlines()
print(words)
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Let us now write a program that accepts a string
from the user and writes it to a text file. Thereafter,
the same program reads the text file and displays it on
the screen.
Program 2-1 Writing and reading to a text file
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line) fileobject.write('\
n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()
In Program 2-5, the file will be read till the time end
of file is not reached and the output as shown in below
is displayed.
Output of Program 2-5:
>>>
RESTART: Path_to_file\Program2-5.py
WRITING DATA IN THE FILE
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
import pickle
print("The data that were stored in file are:
") fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Program 2-8 To perform basic operations on a binary file using pickle module
RECORD No. 1
Employee number : 11
Employee Name : D N Ravi
Basic Salary : 32600
Allowances : 4400
TOTAL SALARY : 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number : 12
Employee Name : Farida Ahmed
Basic Salary : 38250
Allowances : 5300
TOTAL SALARY : 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Record Number : 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number : 2
[12, 'Farida Ahmed', 38250, 5300, 43550]
>>>
As each employee record is stored as a list in the
file empfile.dat, hence while reading the file, a list is
displayed showing record of each employee. Notice that
in Program 2-8, we have also used try.. except block to
handle the end-of-file exception.
SUMMARY
• A file is a named location on a secondary storage
media where data are permanently stored for
later access.
• A text file contains only textual information
consisting of alphabets, numbers and other
EXERCISE
1. Differentiate between:
a) text file and binary file
b) readline() and readlines()
c) write() and writelines()
3. Write the file mode that will be used for opening the
following files. Also, write the Python statements to open
the following files:
a) a text file “example.txt” in both read and write mode
b) a binary file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a binary file “btry.dat” in read only mode.