A file is a named location on a secondary storage
media where data are permanently stored for
later access.
Types of Files
• Every file is basically just a series of bytes
stored one after the other.
• There are mainly two types of data files —
text file and binary file. A text file consists of
human readable characters, which can be
opened by any text editor. On the other hand,
binary files are made up of non-human
readable characters and symbols, which
require specific programs to access its
contents.
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.
• The file contents are stored in sequence of bytes
consisting of 0s and 1s. In ASCII, UNICODE or
any other encoding scheme.
• while opening a text file, the text editor translates
each ASCII value and shows us the equivalent
character that is readable by the human being.
• the default EOL character in Python is newline
(\n).
Binary Files
• Binary files are also stored in terms of bytes (0s
and 1s), but unlike text files, these bytes do not
represent the ASCII values of characters. Rather,
they represent the actual content such as image,
audio, video, compressed versions of other files,
executable files, etc.
• These files are not human readable. Thus, trying
to open a binary file using a text editor will show
some garbage values. We need specific software
to read or write the contents of a binary file.
Opening a file
• To open a file in Python, we use the open()
function.
• The syntax of open() is:
file_object = open(file_name, access_mode)
• We can use this variable to transfer data to and
from the file (read and write) by calling the
functions defined in the Python’s io module.
• If the file does not exist, the above statement
creates a new empty file and assigns it the
name we specify in the statement.
The file_object has certain attributes that tells
us basic information about the file, such as:
<[Link]>
returns true if the file is closed and false
otherwise.
<[Link]>
returns the access mode in which the file was
opened.
<[Link]>
returns the name of the file.
>>>f=open("[Link]","w")
>>>[Link]
'[Link]'
>>> [Link]
'w‘
>>> [Link]
False
>>> [Link]()
>>> [Link]
True
>>> [Link]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
[Link]
NameError: name 'c' is not defined
Opening a file using with clause
with open (file_name, access_mode) as file_ object:
The advantage of using with clause is that any
file that is opened using this clause is closed
automatically, once the control comes outside the
with clause.
with open(“[Link]”,”r+”) as myObject:
content = [Link]()
File Open Modes
Closing a file
• Python provides a close() method to do so.
While closing a file, the system frees the
memory allocated to it. The syntax of close()
is:
file_object.close()
• if the file object is re-assigned to some other
file, the previous file is automatically closed.
Writing to a Text File
• For writing to a file, we first need to open it
in write or append mode.
• If we open an existing file in write mode, the
previous data will be erased, and the file
object will be positioned at the beginning of
the file.
• In append mode, new data will be added at
the end of the previous data as the file
object is at the end of the file.
Methods to write data
in the file
• write() –
for writing a single string
• writelines() –
for writing a sequence of strings
write() method
write() method takes a string as an argument and
writes it to the text file. It returns the number of
characters being written on single execution of the
write() method.
>>> f=open("[Link]","w")
>>> [Link]("HCST")
4
If numeric data are to be written to a text file, the data
need to be converted into string before writing to the
file.
>>> f=open("[Link]","w")
>>> [Link](str(100))
3
writelines()
• This method is used to write multiple strings to
a file. We need to pass an iterable object like
lists, tuple, etc. containing strings to the
writelines() method.
• writelines() does not return any value.
>>> f=open("[Link]","w")
>>> lines=["Hello HCST\n","\n","I am in IT 4
Sem.\n","Name is Gyan Jyoti"]
>>> [Link](lines)
>>> [Link]()
read(n)
This method is used to read a specified number of
bytes of data from a data file. The syntax of read()
method is:
file_object.read(n)
>>> f=open("[Link]","r")
>>> [Link](4)
'Hell‘
If no argument or a negative number is specified
in read(), the entire file content is read.
>>> f=open("[Link]","r")
>>> [Link](-5)
'Hello HCST\n\nI am in IT 4 Sem.\nName is Gyan
Jyoti'
readline([n])
This method reads one complete line from a file
where each line terminates with a newline (\n)
character.
>>> f=open("[Link]","r")
>>> [Link]()
'Hello HCST\n'
It can also be used to read a specified number (n) of
bytes of data from a file but maximum up to the
newline character (\n).
>>> f=open("[Link]","r")
>>> [Link](7)
'Hello H'
If no argument or a negative number is specified,
it reads a complete line and returns string.
>>> [Link]()
'CST\n'
>>> [Link](-2)
'\n'
>>> [Link](-2)
'I am in IT 4 Sem.\n‘
To read the entire file line by line using the
readline(), we can use a loop. This process is known
as looping/ iterating over a file object. It returns an
empty string when EOF is reached.
readlines()
The method reads all the lines and returns the
lines along with newline as a list of strings.
>>> f=open("[Link]","r")
>>> [Link]()
['Hello HCST\n', '\n', 'I am in IT 4 Sem.\n',
'Name is Gyan Jyoti']
lines in the file become members of a list,
where each list element ends with a newline
character (‘\n’).
split() function
In case we want to display each word of a line
separately as an element of a list, then we can use
split() function.
>>> f=open("[Link]","r")
>>> obj=[Link]()
>>> for line in obj:
... words=[Link]()
... print(words)
...
['Hello', 'HCST']
[]
['I', 'am', 'in', 'IT', '4', 'Sem.']
['Name', 'is', 'Gyan', 'Jyoti']
splitlines()
When we use splitlines() then each line is returned
as element of a list, as shown in the output below:
>>> for line in obj:
... words=[Link]()
... print(words)
...
['Hello HCST']
['']
['I am in IT 4 Sem.']
['Name is Gyan Jyoti']
WAP 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.
fobject=open("[Link]","w") # creating a data file
sentence=input("Enter contents to be written in file: ")
[Link](sentence) # Writing data to the file
[Link]() # Closing a file
print("Now reading the contents of the file: ")
fobject=open("[Link]","r")
#looping over the file object to read the file
for str in fobject:
print(str)
[Link]()
if we want to access data in a
random fashion, then Python
gives us seek() and tell()
functions to do so
tell()
This function returns an integer that specifies the
current position of the file object in the file. The
position so specified is the byte position from the
beginning of the file till the current position of
the file object. The syntax of using tell() is:
file_object.tell()
>>> f=open("[Link]","r")
>>> [Link]()
0
>>> [Link](5)
'Hello'
>>> [Link]()
5
>>> [Link]()
' HCST\n\nI am in IT 4 Sem.\nName is Gyan Jyoti'
>>> [Link]()
51
seek()
This method is used to position the file object at a
particular position in a file. The syntax of seek() is:
file_object.seek(offset [, reference_point])
offset is the number of bytes by which the file object
is to be moved. reference_point indicates the starting
position of the file object. That is, with reference to
which position, the offset has to be counted. It can have
any of the following values:
0 - beginning of the file
By default, the value of reference_point is 0, i.e. the
offset is counted from the beginning of the file.
print("Learning to move the file object")
fileobject=open("[Link]","r+")
str=[Link]()
print(str)
[Link]
print("Initially, the position of the file object is:
",[Link]())
[Link](0)
print("Now the file object is at the beginning of the
file:",[Link]())
[Link](10)
print("We are moving to 10th byte position from the
beginning of file")
print("The position of the file object is at", [Link]())
str=[Link]()
print(str)
Output
H:\HCST\2025 - 2026\EVEN
SEM\PYTHON\LAB\Unit 4>python
[Link]
Learning to move the file object
hello\n second \n third \n last
Initially, the position of the file object is: 31
Now the file object is at the beginning of the ile: 0
We are moving to 10th byte position from the
beginning of file
The position of the file object is at 10
cond \n third \n last
reading and writing
operation in a text file
fileobject=open("[Link]", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
[Link](line)
[Link]('\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 ",[Link]())
[Link](0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=[Link]()
print(str)
[Link]()
The Pickle Module
The module Pickle is used for serializing and
de-serializing any Python object structure.
Serialization is the process of transforming data
or an object in memory (RAM) to a stream of
bytes called byte streams. These byte streams in
a binary file can then be stored in a disk or in a
database or sent through a network. Serialization
process is also called pickling.
De-serialization or unpickling is the inverse of
pickling process where a byte stream is
converted back to Python object.
Note
The pickle module deals with binary files.
Here, data are not written but dumped and
similarly, data are not read but loaded.
The Pickle Module must be imported to load
and dump data.
The pickle module provides two methods -
dump() and load() to work with binary files for
pickling and unpickling, respectively.
The dump() method
This method is used to convert (pickling) Python
objects for writing data in a binary file. The file
in which data are to be dumped, needs to be
opened in binary write mode (wb). Syntax of
dump() is as follows:
dump(data_object, file_object)
where data_object is the object that has to be
dumped to the file with the file handle named
file_object.
Example
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("[Link]", "wb")
[Link](listvalues,fileobject)
[Link]()
The load() method
This method is used to load (unpickling) data
from a binary file. The file to be loaded is
opened in binary read (rb) mode. Syntax of
load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from
the file having a file handle named file_object
and is stored in a new file handle called
store_object.
Example
import pickle
print("The data that were stored in file are: ")
fileobject=open("[Link]","rb")
objectvar=[Link](fileobject)
[Link]()
print(objectvar)
O/P
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
Exercise
Write a Program that accepts a record of
an employee from the user and appends
it in the binary file. Thereafter, the
records are read from the binary file and
displayed on the screen using same object.
The user may enter as many records as
they wish to. The program also displays
the size of binary files before starting
with the reading process.
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 special
symbols. Such files .txt, .py, .c, .csv, .html, etc.
Each byte of a text file represents a character.
• Each line of a text file is stored as a sequence of
ASCII equivalent of the characters and is
terminated by a special character, called the End
of Line (EOL).
• Binary file consists of data stored as a stream
of bytes.
• open() method is used to open a file in Python
and it returns a file object called file handle.
The file handle is used to transfer data to and
from the file by calling the functions defined in
the Python’s io module.
• close() method is used to close the file. While
closing a file, the system frees up all the
resources like processor and memory allocated
to it.
• write() method takes a string as an argument
and writes it to the text file.
• writelines() method is used to write multiple
strings to a file. We need to pass an iterable
object like lists, tuple etc. containing strings to
writelines() method.
• read([n]) method is used to read a specified
number of bytes (n) of data from a data file.
• readline([n]) method reads one complete line
from a file where lines are ending with a
newline (\n). It can also be used to read a
specified number (n) of bytes of data from a
file but maximum up to the newline character
(\n).
• readlines() method reads all the lines and
returns the lines along with newline character,
as a list of strings.
• tell() method returns an integer that specifies
the current position of the file object. The
position so specified is the byte position from
the beginning of the file till the current
position of the file object.
• seek()method is used to position the file object
at a particular position in a file.
• Pickling is the process by which a Python
object is converted to a byte stream.