Python File Handling

In this Python file handling tutorial, we will learn how to create, open, read, write and close the file. In this tutorial, we will discuss in detail about reading and write text file as well as a binary file also with the example.

What is a File?

A file is a container, which can contain information or data. In Python, we have the option to create and manipulate such files. In Python, We can divide files into two categories(text and binary).

  • Text File – In the text file, data is store as a character stream.
  • Binary File – In the binary file, data stores in binary (0 or 1) format.

Create, Open and Close a File

In Python, we create or open a file using the open() function and close a file using the close() function.

  • open() – The open(filename,mode) function accept two parameters, filename and mode of file as parameters. If the file exists, it opens the file else create one.
  • close() – The close() function is used close the file.
#open a file in write mode

#close a file

In the above example, f is a variable to store a file, abc.txt is the name of the file which we want to open, w is for write mode, the file will open for write purpose.

Python Read a File

In Python file handling, read() function is used to read the content of the file. The file must exist and open in reading (r) mode.

Read all the content of the file

#open a file in read mode

Read the first 10 characters of the file


Read the first line of the file

readline() – The readline() function, read the first line of the file.


Loop through the file

#read the file line by line
for c in f:

Read the file as a list

readlines() – The readlines() read the whole file, and convert the line as an element of the list.

#read file as a list using readlines() function

Using ‘with’ as a keyword

#using with statement, no need to close the file
with open("xyz.txt","r") as fp:
    for line in fp:

Python File Write

The write() function is used to write data in a file. The file must be open in write(w) mode. It overwrites the content if the file exists.

#open a file in write mode

#write the content to the file
f.write("Hello, I am Learning Python")
f.close()   #close the file

Append Data to a File

To append (write in the existing file) data in a file, write() function is used. The file must be open in append (a) mode.

#open a file in append mode

#append the content to the file
for i in range(0,3):
    roll=input("Enter Your Roll number")
    name=input("Enter Your Name")
f.close()   #close the file

#Now, open and read the content

Python File Modes

In Python, we have a different mode of a file to be open, here is the list of the file mode.

File ModeDescription
‘r’Default mode, opens file in reading mode.
‘w’Open file for writing
‘a’Open file for append
‘x’Create a new file, fails if the file exists.
‘t’Text mode(default).
‘b’Binary mode.
‘+’Opens a file for updating(reading and writing)