File Handling in Python
A file is a named location on disk to store related information. It's used for various purposes, such as
storing data, code, or configuration settings.
Python provides several modules and functions to work with different types of files.
1. Text Files :
Text files in Python are used for storing and reading human-readable text. Each line of text is
terminated with a special character called EOL e.g. \n
e.g. .txt
2. Binary Files:
Binary files store data in the form of bytes in computer readable format. Humans cant understand that.
Module: pickle module is used for working with Binary files.
e.g. .bin
3. CSV Files
CSV (Comma-Separated Values) files are used for storing tabular data. The are a special case
of text file. They are also human readable.
Module : csv module is used for working with CSV files.
e.g. .csv
Opening a File:
• The open() function is used to open a file.
• Syntax: file_object = open(filename, mode)
o filename: The name of the file (e.g., "[Link]").
o mode: Specifies the purpose of opening the file (e.g., "r" for
read, "w" for write, "a" for append, "rb" for binary read, "wb" for binary
write).
Note : readmode has default value ‘r’
f1 = open("[Link]", "r")
or
f1 = open("[Link]")
File object/File Handle : It is an object that represents a file on your computer's file system. It is
created when you open a file using the open() function.
It is a reference to the actual file and is used to do read/write the file on the disk.
file1 = open("[Link]", "r")
file1 is the file object here.
Closing a File:
It's essential to close a file after performing operations to free up system resources.
The close() method is used for this purpose.
Syntax: [Link]()
What is a File Pointer in Python?
A file pointer is like a cursor or marker that shows the current position in a file — i.e., where the next
read or write operation will happen. When you open a file using the open() function, Python
automatically creates a file pointer.
File Opening Modes:
Text Binary Mode File Pointer position
file File Description
/csv
file
r rb read only beginning of the file (i.e. 0). Opens file for reading. If the file does not exist,
raises the I/O error. This is also the default mode
in which a file is opened.
w wb write only beginning of the file (i.e. 0). Opens the file for writing. For the existing files,
All previous data erased/ old data is over-written. Creates a new file if the
truncated file does not exist.
a ab append only End of the file. Open the file for writing. The file is created if it
does not exist. new data will be added at the end
of the file. Old data will be retained.
r+ rb+ read and beginning of the file (i.e. 0). Open the file for reading and writing. Raises I/O
write error if the file does not exist.
w+ wb+ write and beginning of the file (i.e. 0). Open the file for reading and writing. For an
read All previous data existing file, old data is over-written.
erased/truncated
a+ ab+ append End of the file. Open the file for reading and writing.. The file is
and read created if it does not exist. new data will be added to
the end of the file. Old data will be retained.
Path of file:
A path is the location of a file or directory in a file system.
1. Absolute Path: it is the exact location of a file from the root directory. It starts from the root
directory.
absolute_path = "C:/users/documents/[Link]"
2. Relative Path: It is the location of a file relative to the current working directory. current working
directory is the location where your python code file is present. It doesn't start from the root
directory.
relative_path = " documents/[Link]"
[Link] : Sample File to be read
Reading a text file: There are three built-in functions to read a text file.
1. read() or read(n):
Syntax : [Link](n)
• It is a function used to read the entire data of a file if no argument is provided.
• It returns the whole file data as a string.
• This method is typically used when you want to work with the complete data of a file as a
single string.
Output:
If argument n is provided, then it reads the n bytes from the file. Each character of file
is stored in 1 byte.
2. readline(): This function is used to read one line from a file at a time. It returns single
line as a string.
Syntax : [Link]()
3. readlines() : It is used to read all lines from a file and return them as a list. So Each
element of this list corresponds to a line in the file.
Writing/Appending to a text file:
• Step 1: open the file with filename and mode
‘w’ or ‘w+’ is used for writing mode. Old data of file will be lost .New file will be created if file
doesn’t exist.
‘a’ or ‘a+’ is used for append mode. Old data of file will be retained. New data will added at
the end. New file will be created if file doesn’t exist.
• Step 2:
use write() : for adding a single line at a time Use
writelines() : for adding multiple line at a time
There are two methods to write to a text file.
1. write(line) : This function is used to add a single line a time. Single line is a given as
a string.
[Link]
3. writelines(listoflines) :
4.
This function is used to write multiple lines at a time.
These lines are passed as argument in the form of a list.
Writing a text file in append mode:
[Link] write() :
2. using writelines():
with Statement in file handling:
The with statement in Python is a safer and cleaner way to handle files.
Rather than writing
f1 = open(“[Link]”,”r”)
we can write the same the code using with statement
with open(“[Link]”,”r”) as f1:
The biggest advantage — Python automatically closes the file when the code block under with
finishes.
You don’t need to write [Link]().
Even if an error occurs while reading or writing, the file will still be closed safely.
Examples :
tell():
This function returns the current position of file pointer. This function takes no parameters and
returns an integer value. Initially file pointer is at 0 (if not opened in append mode).
Syntax: [Link]()
seek():
This function is used to change the position of the File Pointer to a given
specific position. It is mostly used with binary files.
Syntax: [Link](offset, reference point)
Parameters:
Offset: Number of positions(bytes) to move forward i f o f f s e t i s p o s i t i v e
Number of positions(bytes) to move backward i f o f f s e t i s n e g a t i v e
reference point: It defines point of reference. It can have any three values:
• 0: sets the reference point at the beginning of the file (it is default value you don’t need
to pass it as parameter). Offset is always positive
• 1: sets the reference point at the current file position Offset can be positive or negative
depending upon the current position.
• 2: sets the reference point at the end of the file. Offset is always negative
e.g.
1. [Link](6, 0) or [Link](6) : It means moves file pointer 6 position forward from beginning of the file.
So the current file pointer is at 6.
2. [Link](6, 1) : It means moves file pointer 6 position forward from current position of the of the file
pointer..The current file pointer wass at 6. So now file pointer will at 6+6 = 12.
2. [Link](-6, 2) : It means moves file pointer 6 position backwards from end of the file..
Sample Programs based on text files:
Ques 1. Write a function countVC() that reads a file [Link] and count the no of vowels and
consonants separately.
Ques 2 Write a function countChar() that reads a file [Link] and counts how many characters, digits
, special characters are in the file.
Ques 3 Write a function countCase() that reads a file [Link] and counts the upper and lower
case alphabets. Also displays the count.
Ques 4 Write a function countCase() that reads a file [Link] and counts the occurrence of alphabet p
& v(both case). Also displays the count.
Ques 5 A pre-existing text file [Link] has some words written in it. Write a python function
displaywords() that will print all the words that are having length greater than 3.
Ques 6 Write a function DISPLAYWORDS( ) in python to display the count of words
starting with vowels in a text file ‘[Link]’.
Ques7 Write a function COUNT_AND( ) in Python to read the text file “[Link]” and
count the number of times “AND” occurs in the file. (include AND/and/And in the counting)
Ques: Write a function RevText() to read a text file "[Link]" and Print only word starting with 'I' or
‘i’ in reverse order.
Ques: Write a method COUNTLINES() in Python to read lines from text file ‘[Link]’ and
display the lines which are starting with any article (a, an, the) insensitive of the case.
Ques: Write a Python function that reads lines from [Link] and displays only those starting with P
Ques : A text file “[Link]” contains alphanumeric text. Write a program that reads
this text file and writes to another file “[Link]” entire file except the numbers or
digits in the file.
Ques : Write a function in python to read all the lines in a text file ‘[Link]’ and filter lines which
are starting with an alphabet ‘W’ or ‘H’. and write these lines to '[Link]'
Ques : Write a function in python to read the text file ‘[Link]’ and filter the words which are
starting and ending with a vowel . and write these words to a new text file '[Link]'