In this Tutorial -:

NEXT TUTORIAL >> with statement in Python
Python File Handling is a utility that allow us to play around with file using our cool python code.
Python provides ‘n’ number of functions to perform basic operations on a particular file. These operations may be like opening a file, reading a file, writing a file, closing a file or even deleting a file.
Opening a file with open() function in Python
open() function in python is used to open a file. This file may be a text file or even a binary file.
Syntax of open() function
file = open('filename', 'open_mode', 'buffer')
open() function make use of three parameters :
- filename: represents the name of a file to be opened.
- open_mode: represents the purpose of opening a file
- buffer: represents a temporary block of memory. It denotes an integer value used to set the buffer size for a file(in bytes).
File Opening modes in Python

Above table is specified for text files only.
In case of binary files, we just need to append ‘b’ in the end of modes. Like,
wb, rb, ab, w+b, r+b, a+b are the modes for binary files.
Program: To open a file in read mode
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
print(fp) # printing the file pointer
f.close() # closing a file
O/P
<_io.TextIOWrapper name=’sample.txt’ mode=’r’ encoding=’cp1252′>
Make sure that you are opening a file that already exists or else PVM will be against you.
Reading from a file in Python
Once we open a file in read mode, we can read the content from the file. This can be done using read(), readline() and readlines() functions in Python.
Let’s see how,
sample.txt
Hello World in line 1
Hello World in line 2
Hello World in line 3
Hello World in line 4
Hello World in line 5
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
data = fp.read() # to read all content from file
print(data)
f.close() # closing a file
O/P
Hello World in line 1
Hello World in line 2
Hello World in line 3
Hello World in line 4
Hello World in line 5
read() function in Python is used to read all content from the given file and return it as a string.
read() function also gives us the utility to read the first ‘n’ characters from the given file,
fp.read(n)
where, ‘n’ is the number of bytes to read from beginning of file.
Other option to read a file is using readline() function.
readline() function in Python is used to read the first line from the given file and return it as a string.
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
data = fp.readline() # to read one line from file
print(data)
f.close() # closing a file
O/P
Hello World in line 1
readlines() function in Python is another function used to read the entire content from the given file and return it as a list.
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
data = fp.readlines() # to read all content from file
print(data)
f.close() # closing a file
O/P
[‘Hello World in line 1\n’, ‘Hello World in line 2\n’, ‘Hello World in line 3\n’, ‘Hello World in line 4\n’, ‘Hello World in line 5\n’]
Like read(), both readline() and readlines() functions also support reading first ‘n’ lines from a file.
Closing a file in Python
A file that is opened is eligible to be closed. This can be done using close() function in Python. It is the best practice to close a file once its usage is done to avoid any ambiguity or file corruption. It could happen while working with multiple files.
f = open('sample.txt', 'r') # opening a file
f.close() # closing a file
Writing an existing file in Python
If you want to add some content in an existing file, there are two ways to achieve this.
“a” – Append – will append to the end of the file
“w” – Write – will overwrite any existing content
fp = open('sample.txt', 'a') # opening a file sample.txt in append mode
fp.write('Say No Hello world') # to append a content to file
f.close() # closing a file
O/P (sample.txt)
Hello World in line 1
Hello World in line 2
Hello World in line 3
Hello World in line 4
Hello World in line 5
Say No Hello world
fp = open('sample.txt', 'w') # opening a file sample.txt in write mode
fp.write('Say No Hello world') # to write a content to file
f.close() # closing a file
O/P (sample.txt)
Say No Hello world
Observe how previous content of file was overridden by the new one.
Creating a new file in Python
To create a new file in Python, we should use the open() method, with one of the following parameters:
“x” – Create – will create a file, returns an error if the file exist
“w” – Write – will create a file if the specified file does not exist
“a” – Append – will create a file if the specified file does not exist
f = open("sample.txt", "x")
OR
f = open("sample.txt", "w")
OR
f = open("sample.txt", "a")
Checking if file exists in Python or not
In order to do file operations, if we want to pre-check whether that particular file exists or not, we can make use of os module in python.
import os
if os.path.isfile('sample.txt'):
f = open('sample.txt', 'r')
print(f.read())
else:
print('Given file does not exists.')
Given method os.path.isfile(filename), returns True if files exists in the given path else it returns False.
seek() and tell() function in Python
tell() function in Python is used to find the current position of the file pointer from the beginning in the given file.
f.tell()
seek() function in Python is used to bring the file pointer to the given specified position.
f.seek(offset, position)
offset: It represents how many bytes to move.
position: It represents from which position file pointer should move.
Let’s see their application,
Consider a file sample.txt has following content in it,
Hello World
fp = open('sample.txt', 'r') # opening a file sample.txt in read mode
print(fp.read())
print(fp.tell()) # prints 11 as file pointer comes at the last position while reading file
fp.seek(2) # pulling file pointer to second position
print(fp.tell()) # prints 2 as we just seek file pointer to second position
print(fp.read()) # read content from position 2 (0-based index)
O/P
Hello World
11
2
llo World
That’s all in “File Handling in Python”.
NEXT TUTORIAL >> with statement in Python
