Process Advisors

*Subject to Terms and Condition

File Handling in Python

Python file handling operations are also known as Python I/O deal with two types of files. They are:

  • Text files
  • Binary files

Even though the two file types may look the same on the surface, they encode data differently.

A text file is structured as a sequence of lines. And, each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted with the end of line (EOL). There are a few special characters that are used as EOL, but comma {,} and newlines are the most common ones.

Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files.

Watch this video on ‘Python File Handling’:

Become a Professional Python Programmer with this complete Python Training in Singapore!

Now that we have got an idea of what text and binary files are, we are ready to dive into the discussion of different file handling methods and python file operations. Following is the list of all topics covered in this module:

So, without further delay, let’s get started.

Creating a File

To create a new file in Python, you can use the open() method, along with one of the given parameters:

"x" - Create - will create a file, returns an error if the file exists
"w" - Write - will create a file if it doesn’t exist
"a" - Append - will create a file if it doesn’t exist
f = open("myfile.txt", "x")

Opening a File

To open a file, the built-in Python Function open() is used. It returns an object of the file which is used along with other functions.

Syntax of the Python open function:

obj=open(file_name , access_mode, buffer)


  • The file_name refers to the file which we want to open.
  • The access_mode specifies the mode in which the file has to be opened. It can be ‘r’, which is used for opening a file only to read it in Python, or ‘w’ used for opening a file only to write into it. Similarly, ‘a’ opens a file in Python in order to append, and so on. For more access modes, refer to the table given below.
  • The buffer represents whether buffering is performed or not. If the buffer value is 0, then no buffering is performed, and when the buffer value is 1, then line buffering is performed while accessing the file.

Some of the most common access modes are listed below:

Modes Description
r Opens a file only for reading
rb Opens a file only for reading but in a binary format
w Opens a file only for writing; overwrites the file if the file exists
wb Opens a file only for writing but in a binary format
a Opens a file for appending. It does not overwrite the file, just adds the data in the file, and if file is not created, then it creates a new file
ab Opens a file for appending in a binary format

Here’s an example of Python open function and Python readlines for reading files line by line. Say, this is how our text file, ‘demofile.txt’ looks like:

This is just a text file
But this is a newline

Now here’s a code snippet to open the file using file handing in Python.

f= open(‘demofile.txt’, ‘r’)

With the help of the open function of Python read text file, save it in a file object and read lines with the help of the readlines function. Remember that f.readline() reads a single line from the file object. Also, this function leaves a newline character (\n) at the end of the string.


‘This is just a text file,\n’

Go for this in-depth job-oriented Python Training in Hyderabad now!

Writing into a File

The write() method is used to write a string into a file.

Syntax of the Python write function:



i.write(“Hello Intellipaat”)

Here, we are opening the demotext.txt file into a file object called ‘i’. Now, we can use the write function in order to write something into the file.

Reading from a File

The read() method is used to read data from a file.

Syntax of the Python read function:




Hello Intellipaat

Closing a File

The close() function is used to close a file.

Syntax of the Python close function:





Hello Intellipaat

We have the perfect professional Python Course in Bangalore for you!

Deleting a File

To delete a file in Python, you have to import the module OS, and use the os.remove() function.

import os

Checking if a File Exists

When trying to delete a file, it is a good idea to check if the file exists or not, to avoid getting an error.

import os
if os.path.exists("demofile.txt"):
  print("The file does not exist")

Further, check out our offers for Python training Courses and also refer to the trending Python interview questions and answers prepared by the industry experts.

Methods of File Handling in Python

There are different file handling in Python which are as follows:

  1. rename(): This is used to rename a file.
import os
os.rename(existing file_name, new file_name)
  1. remove(): This method is used to delete a file in Python.
import os
  1. chdir(): This method is used to change the current directory.
import os
os.chdir(“new directory path”)
  1. mkdir(): This method is used to create a new directory.
import os
os.mkdir(“new directory path “)
  1. rmdir(): This method is used to remove a directory.
import os
os.rmdir(“new directory path”)
  1. getcwd(): This method is used to show the current working directory.
import os

Other Methods of File Handling in Python

Following are the other common methods of file handling in Python, along with their descriptions

Method Description
close() To close an open file. It has no effect if the file is already closed
flush() To flush the write buffer of the file stream
read(n) To read at most n characters from a file. Remember that it reads till end of file if it is negative or none
readline(n=-1) To read and return one line from a file. Remember that it reads at most n bytes, if specified
readlines(n=-1) To read and return a list of lines from a file. Remember that it reads at most n bytes/characters if specified
seek(offset,from=SEEK_SET) It changes the file position to offset bytes, in reference to  (start, current, or end)
tell() It returns the current file location
writable() It returns true if the file stream can be written to
write(s) To write string s into a file and return the number of characters written
writelines(lines) To write a list of lines into a file

So, here’s the end of the Python file handling tutorial, where we answered the question, ‘What is file handling in Python?’ Here, we have also discussed different file handling in Python with examples that will be helpful while working on real-world projects.
With this, we come to the end of this module on Python Tutorial.

Now, let us go ahead and discuss how to make our program more robust and secure from potential failures. Now, if you want to know why Python is the most preferred language for data science, you can go through this on Python Data Science tutorial.

Course Schedule

Name Date Details
Python Course 03 Jun 2023(Sat-Sun) Weekend Batch
View Details
Python Course 10 Jun 2023(Sat-Sun) Weekend Batch
View Details
Python Course 17 Jun 2023(Sat-Sun) Weekend Batch
View Details

1 thought on “Python File Handling - How to Create, Open, Read & Write”

  1. this video was great and I understood file handling well
    thank you!
    btw do you have videos on python modules and using packages?

Leave a Reply

Your email address will not be published. Required fields are marked *