FILE HANDLING
Why there is a need of File Handling?
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.
TYPES OF FILES
✓ Text Files
✓ Binary Files
✓ CSV Files
TEXT FILES
✓ American Standard Code for information, Interchange
✓ Stores information in ASCII or Unicode characters.
✓ Each line of text is terminated with a special character known as EOL
(End of Line) ('\n', '\r n').
✓ Internal translations take place when EOL is read.
✓ Extension for text files is.txt
✓ Default mode of file.
BINARY FILE
✓ Contains information in the same format in which the information is held
in memory.
✓ There is no delimiter for a line.
✓ No translations are required.
✓ Faster than text files.
✓ More secure.
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES
Text File Binary File
Text files stores information in ASCII Binary files are used to store binary
characters. data 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
because these files are in human understand.
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
CSV FILES
✓ Comma Separated Values (CSV) file.
✓ Simple file in human readable format.
✓ Used to store tabular data in plain text.
✓ By default, Delimiter is comma.
✓ Easy to generate and import onto a spreadsheet or database.
FILE ACCESS MODES
Mode Description
r Opens file for reading only. This is the Default Mode
rb Opens file for reading only in Binary format. This is the Default
Mode
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in Binary format
w Opens a file for writing only. Overwrites the file if already exists,
else creates a new file
wb Opens a file for writing only in Binary format.
w+ Opens a file for both reading and writing
wb+ Opens a file for both reading and writing in Binary format
a Opens a file for appending. The file pointer is at the end of the file
if the file exists. If the file does not exist, it creates a new file for
writing.
ab Opens a file for appending in Binary format.
a+ Opens a file for both appending and reading
ab+ Opens a file for both appending and reading in Binary format
FILE ACCESS MODES
r - Read Only
✓ If file exists, it will read data from the file.
✓ If the file doesn't exists, Python will raises an error.
W - Write Only
✓ If the file does not exist, file is created.
✓ If the file exists, Python will truncate existing data and overwrite the file.
a - Append
✓ New data will be added to the end of existing data, no overwriting.
✓ If file does not exist, Python will create a new file.
r+ - Read and Write
✓ File must exist otherwise error is raised.
✓ Both reading and writing can take place.
w+ - Write and Read
✓ File is created if not exists.
✓ If exists data will be truncated.
✓ Both write and read allowed.
a+ - Append and Read
✓ File is created, if not exists.
✓ If file exists, new data will be added at the end of the file.
✓ Both read and write allowed.
DIFFERENCE BETWEEN r+ AND w+ MODE
r+ mode w+ mode
Used for both reading and writing W+ mode is also used for both
reading and writing.
In r+ mode, the file pointer is at the In w+ mode, the file pointer is at the
beginning of the file. beginning of the file.
If the file does not exists, it will If the file does not exist, it will create
display the FileNotFound Error. the new file.
If the file exist, it doesn't show any If the file exists, it will write the data
error. in the file (overwriting the previous
content).
OPENING A TEXT FILE
Two methods to open a File.
✓ Using open () function
✓ Using with statement
HOW TO OPEN A TEXT FILE ?
Using open()
SYNTAX
FileObject = open(<filename>)
OR
FileObject = open(<filename>, <mode>)
File Handle Path to a file Mode of a file
or
File object created.
EXAMPLE
F = open("myfile.txt",'r')
Myfile.txt and.py file, both are saved at same location.
F= open ("C:\\Users.txt", "г")
First argument specifies the path of the file. The slashes in the path must be
doubled
F = open (r"C:\Users\sony\Desktop\TextFile.txt", "r")
Another solution of double backslash is using "r" before the path making
the string as raw string i.e. no special meaning attached to any character
Using with statement
This method is very handy when you have two related operations
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("....")
EXAMPLE
with open ("Output.txt","w") as f:
f.write ("Text")
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.
POINTS TO REMEMBER
✓ The default file open mode is read mode .
✓ If mode is not specified, Python will open in read mode.
✓ When you open a file in read mode, the given file must exist in the folder,
otherwise Python will raise FileNotFoundError.
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])
EXAMPLE 01
f=open("Sam.txt",'r')
data2=f.read(4)
print(data2)
print(type(data2))
f.close()
OUTPUT
Welc
<class 'str'>
EXAMPLE 02
f=open("Sam.txt",'r')
data3=f.read(15)
print(data3)
print(type(data3))
f.close()
OUTPUT
Welcome to the
<class 'str'>
EXAMPLE 03
f=open("Sam.txt",'r')
data=f.read()
print(data)
print(type(data))
f.close()
OUTPUT
Welcome to the World of Programming Languages.
Python is a great language to learn.
Begin your coding journey now!
<class 'str'>
readline()
✓ 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()
EXAMPLE 01
f=open("Sam.txt",'r')
data=f.readline()
print(data)
print(type(data))
data2=f.readline()
print(data2)
print(type(data2))
data3=f.readline()
print(data3)
print(type(data3))
data4=f.readline()
print(data4)
print(type(data4))
OUTPUT
Welcome to the World of Programming Languages.
<class 'str'>
Python is a great language to learn.
<class 'str'>
Begin your coding journey now!
<class 'str'>
<class 'str'>
EXAMPLE 02
f=open("Sam.txt",'r')
data=f.readline()
print(data,end='')
print(type(data))
data2=f.readline()
print(data2, end='')
print(type(data2))
data3=f.readline()
print(data3, end='')
print(type(data3))
data4=f.readline()
print(data4, end='')
print(type(data4))
OUTPUT
Welcome to the World of Programming Languages.
<class 'str'>
Python is a great language to learn.
<class 'str'>
Begin your coding journey now!<class 'str'>
<class 'str'>
EXAMPLE 03
f=open("Sam.txt",'r')
data=f.readline(4)
print(data,end='')
print(type(data))
data2=f.readline(2)
print(data2, end='')
print(type(data2))
data3=f.readline()
print(data3, end='')
print(type(data3))
OUTPUT
Welc<class 'str'>
om<class 'str'>
e to the World of Programming Languages.
<class 'str'>
readlines()
✓ Reads all the lines of a text file.
✓ Returns in the form of list.
✓ Syntax
<FileHandle>.readlines()
EXAMPLE 01
f=open("Sam.txt",'r')
data=f.readlines()
print(data)
print(type(data))
OUTPUT
['Welcome to the World of Programming Languages. \n', 'Python is a great
language to learn. \n', 'Begin your coding journey now!']
<class 'list'>
HOW TO WRITE DATA IN A FILE?
✓ write()
✓ writelines()
WHILE 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 a 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.
✓ Syntax
<filehandle>.write(str)
WRITING DATA IN A TEXT FILE
EXAMPLE 01
f=open("Sample.txt","w")
f.write("C")
f.write("C++")
f.write("Java")
f.write("C#")
f.write("Python")
f.close()
OUTPUT
CC++JavaC#Python
EXAMPLE 02
f=open("Sample.txt","w")
f.write("C\n")
f.write("C++\n")
f.write("Java\n")
f.write("C#\n")
f.write("Python\n")
f.close()
OUTPUT
C
C++
Java
C#
Python
writelines(seq)
writelines() method is used to write sequence data types in a file(string,
list and tuple etc.)
EXAMPLE 01
f=open("Sam1.txt","w")
f.writelines(['11','22','33'])
f.close()
OUTPUT
112233
EXAMPLE 02
f=open("Sam1.txt","w")
f.writelines([11,22,'33'])
f.close()
OUTPUT
Traceback (most recent call last):
File "D:/Academics/Grade XII CS 2025-2026/Revision/File Handling/Text
File/writelineexample2.py", line 2, in <module>
f.writelines([11,22,'33'])
TypeError: write() argument must be str, not int
APPENDING DATA TO A FILE....
✓ Append means to add the data at the end of file using 'a' mode.
✓ If file doesn't exists, it will create the new file.
✓ If file exists, it will append the data at the end of a file.
EXAMPLE 01
f=open("Sam2.txt","a")
f.write("Welcome")
f.close()
OUTPUT
Welcome
EXAMPLE 02
f=open("Sam2.txt","a")
f.write("to the world of Programming.")
f.close()
OUTPUT
Welcometo the world of Programming.
CLOSING FILES
✓ 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 file object or
file - handle.
✓ Syntax
<FileHandle>.close()
✓ Example
F.close()
RANDOM ACCESS IN FILES
✓ seek()
✓ tell()
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
f.seek(offset, from_what)
#where f is file pointer
✓ Offset is number of bytes to move.
✓ The reference point is defined by the "from_what" argument. It can have
any of the three values:
✓ 0: sets the reference point at the beginning of the file, which is by default.
✓ 1: sets the reference point at the current file position.
✓ 2: sets the reference point at the end of the 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 the file
in b mode.
tell()
✓ tell () is used to tell the current position of a file pointer.
Sam.txt
Welcome to the World of Programming Languages.
Python is a great language to learn.
Begin your coding journey now!
EXAMPLE 01
f=open("Sam.txt","r")
print(f.read(2))
print(f.tell())
f.close()
OUTPUT
We
2
EXAMPLE 02
f=open("Sam.txt","r")
f.seek(4) #moves the pointer 4 bytes from beginning
print(f.tell())
print(f.read(3))
print(f.tell())
f.close()
OUTPUT
4
ome
7
EXAMPLE 03
f=open("Sam.txt","a")
print(f.tell())
f.close()
OUTPUT
118
EXAMPLE 04
f=open("Sam.txt", "r+") #read & Write
print(f.tell())#In r+ mode pointer at the beginning
print(f.read(2))
f.write("PPP")
f.seek(0)#Move the pointer to the beginning
print(f.read())
f.close()
OUTPUT
0
We
Welcome to the World of Programming Languages.
Python is a great language to learn.
Begin your coding journey now!PPP
EXAMPLE 05
f=open("Sam.txt","r+")
print(f.tell())
f.seek(2)#Overwrite
f.write("PPP")
f.seek(0)
print(f.read())
f.close()
OUTPUT
0
WePPPme to the World of Programming Languages.
Python is a great language to learn.
Begin your coding journey now!
EXAMPLE 06
Sam2.txt
Welcome to the world of Programming.
f=open("Sam2.txt", "w+")
print(f.tell())
f.write("Programming World")
f.seek(0)
print(f.read(3))
f.close()
OUTPUT
0
Pro
EXAMPLE 07
f=open("Sam2.txt", "w+")
print(f.tell())
f.write("Welcome")
f.seek(0)
print(f.read(1))
f.seek(2)
f.write("##@@")
print(f.read())
f.close()
OUTPUT
0
W
e