File Handling in Python with Example Programs

This article is intended to cover all aspects of file handling, including example programs and sample runs or outputs. As a result, this file handling tutorial is intended to make you feel at ease right away.

One of the most popular topics in Python is file handling. Because we sometimes need to use our Python program to insert, update, or delete information in or from the file.

What did this post cover regarding file handling in Python?

The list of topics that are going to be covered in this post is as follows:

The most commonly used file handling function is "open()." Because every time we want to perform an operation on a file, we must first open it, and this function is used to do so.

Note: Depending on the opening modes, the file is opened for reading, writing, appending, and so on.

Why is file handling required in Python?

The handling of files is an important aspect of developing web applications in Python. The majority of the time, data must be stored in the form of files. The data could be textual information, images, videos, and so on.

Python file handling methods

Here is a list of all the important methods, with brief descriptions, that are used to handle files in Python. In all of these methods, open(), read(), write(), and close() are the most commonly used methods for file handling.

Other than these four methods, file handling falls under the advanced category. I've covered both the basic and advanced versions of file handling in this tutorial. So let me first describe those important methods that play a key role while handling the file in Python:

List of Important File Opening Modes

The most commonly used modes while handling the file in Python programming are given below. To learn about all the modes, you need to refer to the open() function. There, I've described every detail, as well as all the modes and examples.

Basics of File Handling in Python

Let me cover the basics of file handling in Python first. Then we will cover all the advanced topics of file handling. Under the basic section, we'll deal with these operations:

Let's start with the first one, which is opening the file.

Python File Open Operation

In Python, to open a file, we need to use the open() function. Here is an example: opens a file named myfile.txt.

c = open("myfile.txt")

Since I've not provided the mode and because the default mode is r, therefore, the above file is opened in r, or read-only, mode.

Python File Create Operation

To create a file in Python, we need to open the file in w, w+, wb, wb+, a, a+, ab, ab+ mode. As already mentioned, all the modes that go along with these modes are described in the open() function. For now, we only need r, w, and a modes.

file_handler = open("myfile.txt", "w")
print("The file \"myfile.txt\" is created.")

If you execute this Python program, then, using the first statement, a file named myfile.txt will be created in the current directory. The directory in which your Python source code is savedAnd the output produced by the above program using its second statement will be:

python file handling

Because I save my Python source code, or the above program, in the directory C:\Users\DEV\codescracker, the file is created within this. Here is the snapshot of the directory along with the newly created file using the above program's sample run:

python file input output

Because I've not written anything to this file, the size of the file is 0. That is, no content is available in this file for now.

Python File Write Operation

since the file was created using the above program. Therefore, it's time to add content to the file. So let's write using the program given below:

file_handler = open("myfile.txt", "w")
file_handler.write("Hey, I'm the content.")
print("The content is written in the file.")

As you can see, before writing the content using write(), we need to open the file in writing mode, i.e., w. Now if you execute the above program, then the content "Hey, I'm the content" will get written in the file. And a message says: "The content is written in the file" and will be printed on the output console. Here is a snapshot of the sample output produced by the above program:

python file handling programs

Now if you open the file, it contains some content this time, written using the above program. Here is a snapshot of the opened file:

file handling in python

Python File Read Operation

As the file is created, some content is also written to the file using previous programs. As a result, it is now time to read the content from the file. So the following program opens the same file in reading mode with r to read the content available in it:

file_handler = open("myfile.txt", "r")
print(file_handler.read())

The output produced by the above program will be the text available in the file myfile.txt. Here's a screenshot of the sample output:

python file handling example

Another way to read a file is:

file_handler = open("myfile.txt", "r")
for line in file_handler:
   print(line, end="")
file_handler.close()

Note: The end= parameter in print() is used to skip automatic newline insertion.

Python File Close Operation

After performing the operation (such as read, write, update, etc.) to or from the file, we need to close the linkage of the file from the program using its handler. Therefore, Python provides a function named close() that is used to do this task. Here is the program that demonstrates it:

file_handler = open("myfile.txt", "r")
file_handler.close()
print("The file is closed.")

If you execute the above program, the output will be:

The file is closed.

Let's create another program that shows what happens when we read the file after closing it.

file_handler = open("myfile.txt", "r")
file_handler.close()
print(file_handler.read())

This time, the output of the aforementioned program will be:

python file handling close file

That is, the file handler code file_handler.read() within the print() function raises an exception named ValueError saying "I/O operation on closed file," or we cannot perform input or output operations on a file that is closed.

Let's create another program that handles the error manually.

file_handler = open("myfile.txt", "r")
file_handler.close()
try:
   content = file_handler.read()
   print(content)
except ValueError:
   print("The file is closed.")

After catching the error and putting the manual error message inside the except block, the output will now be the manual message I gave. Here is the output produced:

The file is closed.

And if you remove the statement:

file_handler.close()

from above program, then the output will be:

Hey, I'm the content.

where "Hey, I'm the content," is the content available in the file myfile.txt?

Advance File Handling in Python

Since all the basics of file handling are covered. Now let's move on to cover some interesting and advanced topics related to file handling in Python.

Create a file only if that file does not exist

This is the most important section of advanced file handling in Python. I think most of the time we use the w mode to create a file without knowing whether a file with the same name already exists in the directory or not. Because if the same file already exists, then using write mode will overwrite the file, or the file's content will get deleted.

We may lose some important data because the file content will get deleted. Therefore, we need to check whether the file that we're going to create already exists or not. If not, then we must create the file.

print("Enter the Name of File: ", end="")
file_name = input()
try:
   file_handler = open(file_name, "x")
   print("\nThe file named \"", file_name, "\" is created.", sep="")
except FileExistsError:
   print("\nThe file named \"", file_name, "\" is already available.", sep="")

Note: The x mode is used in place of w to create a file only if the file does not exist. Otherwise, it returns an error, i.e., FileExistsError.

Here is its sample run with user input myfile.txt as the name of the file to create:

python file handling create file if not exist

You can examine the contents of myfile.txt.Everything will be untouched using the above program. Here is another sample run with user input yourfile.txt as the name of the file to create:

python file handling basics

If you see your current directory, then the file named yourfile.txt will be available, as created using the above program's sample run:

Check if a file is writable

Before writing content to a file, it is good practice to check whether the file is writable or not. Therefore, the function writable() can be used to do this job, as shown in the program given below:

print("Enter the Name of File: ", end="")
file_name = input()
file_handler = open(file_name, "w")
if file_handler.writable():
   print("\nThe file, \"", file_name, "\" is writable.", sep="")
   print("\n1. Write at Once")
   print("2. Write Line by Line")
   print("Enter Your Choice (1 or 2): ", end="")
   choice = int(input())
   if choice==1:
      print("\nEnter text to write: ", end="")
      content = input()
      file_handler.write(content)
   elif choice==2:
      print("\nHow many lines to write: ", end="")
      no_of_lines = int(input())
      print("Enter", no_of_lines, "lines of string to write: ", end="")
      mylines = list()
      for i in range(no_of_lines):
         line = input()
         line = line + "\n"
         mylines.append(line)
      file_handler.writelines(mylines)
      print("\nLines are written in the file.")
   else:
      print("\nInvalid Choice!")
else:
   print("\nThe file, \"", file_name, "\" is not writable.", sep="")
file_handler.close()

Here is its sample run with the following user inputs:

The snapshot given below shows the sample run using the above user inputs:

python file handling write file if writable

In the above program, the statement is:

line = line + "\n"

is used to insert a newline at the end of every line. To learn more about the writable() function, refer to its separate tutorial.

Note: The file may not be writable because the opening mode does not allow it or the permission is not allowed.

Check if a file is readable

This program is similar to previous ones. That is, in this program, I've also checked whether the file is readable or not before actually performing the read operation on it. Also, I've applied all three ways to read the content of a file:

print("Enter the Name of File: ", end="")
file_name = input()
file_handler = open(file_name, "r")
if file_handler.readable():
   print("\nThe file, \"", file_name, "\" can be read.", sep="")
   print("\n1. Read Whole Content")
   print("2. Read First Line")
   print("3. Read Content by Lines")
   print("Enter Your Choice (1, 2, or 3): ", end="")
   choice = int(input())
   if choice==1:
      print("\n----Content of File----")
      content = file_handler.read()
      print(content)
   elif choice==2:
      print("\n----Content of File----")
      content = file_handler.readline()
      print(content)
   elif choice==3:
      print("\n----Content of File----")
      content = file_handler.readlines()
      print(content)
   else:
      print("\nInvalid Choice!")
else:
   print("\nThe file, \"", file_name, "\" can not be read.", sep="")
file_handler.close()

Here is its sample run with user inputs, myfile.txt as file name, and 2 as choice:

python file handling read file

Here is another sample run with 3 as choice this time:

python file handling read file if readable

And if you go with the first choice, then the output will be:

This is the first line.
This is the second line.
This is the third line.

Python File Append Operation

In the basic section of file handling in Python, I covered the topic of writing to a file. Therefore, let me create a program that shows how to append the new content to a file  without deleting the previous one.

print("Enter the Name of File: ", end="")
file_name = input()
file_handler = open(file_name, "a+")
print("\nEnter the content to append: ", end="")
content = input()
file_handler.write(content)
file_handler.seek(0)
print("\n----New content of file----")
print(file_handler.read())
file_handler.close()

Here is its sample run with user input as the same file name as provided in previous programs and content to append as "This is the string on fourth line"

python file handling appending to file

Note: The a+ mode is used to open the file in both appending and reading mode. And seek() is used to move the position of the file object or handler in the file stream. Because I've used seek(0), the file handler will go to the beginning of the file in the file stream.

The above program can also be replaced with the program given below:

print("Enter the Name of File: ", end="")
file_name = input()
file_handler = open(file_name, "a")
print("\nEnter the content to append: ", end="")
content = input()
file_handler.write(content)
file_handler.close()
file_handler = open(file_name, "r")
print("\n----New content of file----")
print(file_handler.read())
file_handler.close()

This program works exactly the same as the previous program. The only difference is that instead of opening the file in both reading and appending mode, I opened it in appending mode first to append the content.

When the content is appended, then I've closed the file using its handler. And re-open the file in reading mode using r to read the content of the file instead of using seek() to move the handler at the beginning to read the content. You can follow any method to do the job. However, for beginners, I recommend the second option; otherwise, the first is preferable.

Python File Update Operation

Appending to a file is also a way that can be considered as "updating" the file. But this section contains the actual update of the content of a file. That is, here we will replace some text with the new text. Let's see how. Here is a program that demonstrates it:

print("Enter the Name of File: ", end="")
file_name = input()
file_handler = open(file_name, "r")
content = file_handler.read()
print("\nEnter the text to search: ", end="")
old_text = input()
if old_text in content:
   print("Enter new text to replace with: ", end="")
   new_text = input()
   content = content.replace(old_text, new_text)
   file_handler.close()
   file_handler = open(file_name, "w")
   file_handler.write(content)
   print("\nThe text is replaced!")
   print("\nWant to read (y/n): ", end="")
   ch = input()
   if ch=='y':
      file_handler.close()
      file_handler = open(file_name, "r")
      print("\n----New content of file----")
      print(file_handler.read())
else:
   print("\nThe text, \"", text, "\" is not found in the file.")
file_handler.close()

Here is a sample run with the user input myfile.txt, "line" as the text to search for, "string" as the text to replace, and finally "y" as the option to display the file's new content after the replace operation:

python file handling update file

Mega Program on File Handling in Python

Since all the topics of file handling in Python are covered. Therefore, let me combine all those topics and create a mega-program on file handling. This program includes all of these things, along with the handling of all errors. Do concentrate on the program and its sample run. Trust me, after understanding this program, you'll feel better than ever before in the field of file handling in Python.

print("1. Read a File")
print("2. Write to File")
print("3. Append to File")
print("4. Update a File")
print("Enter Your Choice (1-4): ", end="")
try:
   choice = int(input())
   if choice==1:
      print("\nEnter the Name of File: ", end="")
      file_name = input()
      try:
         file_handler = open(file_name, "r")
         if file_handler.readable():
            print("\n----Content of File----")
            print(file_handler.read())
         else:
            print("\nThe file is not readable.")
         file_handler.close()
      except FileNotFoundError:
         print("\nFile not found!")
   elif choice==2:
      print("\nEnter the Name of File: ", end="")
      file_name = input()
      file_handler = open(file_name, "w")
      if file_handler.writable():
         print("\n1. Write text of single line.")
         print("2. Write text of multiple lines.")
         try:
            option = int(input())
            if option==1:
               print("\nEnter text to write: ", end="")
               text = input()
               file_handler.write(text)
               print("\nThe text is written in the file.")
               print("Want to read (y/n) ? ", end="")
               ch = input()
               if ch=='y':
                  file_handler.close()
                  file_handler = open(file_name, "r")
                  print("\n----Content of File----")
                  print(file_handler.read())
                  file_handler.close()
            elif option==2:
               print("\nHow many number of lines to write: ", end="")
               try:
                  no_of_lines = int(input())
                  print("Enter", no_of_lines, "lines of text, one by one:")
                  mylines = list()
                  for i in range(no_of_lines):
                     line = input()
                     line = line + "\n"
                     mylines.append(line)
                  file_handler.writelines(mylines)
                  print("\nAll lines are written in the file.")
                  print("Want to read (y/n) ? ", end="")
                  ch = input()
                  if ch=='y':
                     file_handler.close()
                     file_handler = open(file_name, "r")
                     print("\n----Content of File----")
                     print(file_handler.read())
                     file_handler.close()
               except ValueError:
                  print("\nInvalid Input! (number of lines)")
            else:
               print("\nInvalid Option!")
         except ValueError:
            print("\nInvalid Input! (Option)")
      else:
         print("\nThe file is not writable.")
   elif choice==3:
      print("\nEnter the Name of File: ", end="")
      file_name = input()
      file_handler = open(file_name, "a")
      if file_handler.writable():
         print("\n1. Append text of single line.")
         print("2. Append text of multiple lines.")
         try:
            option = int(input())
            if option==1:
               print("\nEnter text to append: ", end="")
               text = input()
               file_handler.write("\n")
               file_handler.write(text)
               print("\nThe text is appended in the file.")
               print("Want to read (y/n) ? ", end="")
               ch = input()
               if ch=='y':
                  file_handler.close()
                  file_handler = open(file_name, "r")
                  print("\n----Content of File----")
                  print(file_handler.read())
                  file_handler.close()
            elif option==2:
               print("\nHow many number of lines to append: ", end="")
               try:
                  no_of_lines = int(input())
                  print("Enter", no_of_lines, "lines of text, one by one:")
                  mylines = list()
                  for i in range(no_of_lines):
                     line = input()
                     line = line + "\n"
                     mylines.append(line)
                  file_handler.write("\n")
                  file_handler.writelines(mylines)
                  print("\nAll lines are appended in the file.")
                  print("Want to read (y/n) ? ", end="")
                  ch = input()
                  if ch=='y':
                     file_handler.close()
                     file_handler = open(file_name, "r")
                     print("\n----Content of File----")
                     print(file_handler.read())
                     file_handler.close()
               except ValueError:
                  print("\nInvalid Input!")
            else:
               print("\nInvalid Option!")
         except ValueError:
            print("\nInvalid Input!")
      else:
         print("\nThe file is not writable.")
   elif choice==4:
      print("\n1. Replace Text")
      print("2. Delete Text")
      print("3. Empty File")
      print("Enter your choice (1-3): ", end="")
      try:
         option = int(input())
         print("\nEnter the Name of File: ", end="")
         file_name = input()
         file_handler = open(file_name, "r")
         content = file_handler.read()
         if option==1:
            print("Enter text to search: ", end="")
            old_text = input()
            if old_text in content:
               print("Enter text to replace with: ", end="")
               new_text = input()
               content = content.replace(old_text, new_text)
               file_handler.close()
               file_handler = open(file_name, "w")
               file_handler.write(content)
               print("\nThe text is replaced!")
               file_handler.close()
               print("Want to read (y/n) ? ", end="")
               ch = input()
               if ch == 'y':
                  file_handler = open(file_name, "r")
                  print("\n----Content of File----")
                  print(file_handler.read())
                  file_handler.close()
            else:
               print("\nThe text is not found in the file!")
         elif option==2:
            print("Enter text to delete: ", end="")
            text_to_delete = input()
            if text_to_delete in content:
               content = content.replace(text_to_delete, "")
               file_handler.close()
               file_handler = open(file_name, "w")
               file_handler.write(content)
               print("\nThe text is deleted!")
               file_handler.close()
               print("Want to read (y/n) ? ", end="")
               ch = input()
               if ch == 'y':
                  file_handler = open(file_name, "r")
                  print("\n----Content of File----")
                  print(file_handler.read())
                  file_handler.close()
            else:
               print("\nThe text is not found in the file!")
         elif option==3:
            file_handler.close()
            file_handler = open(file_name, "w")
            file_handler.write("")
            print("\nThe file is emptied!")
            file_handler.close()
            print("Want to read (y/n) ? ", end="")
            ch = input()
            if ch == 'y':
               file_handler = open(file_name, "r")
               print("\n----Content of File----")
               print(file_handler.read())
               file_handler.close()
         else:
            print("\nInvalid Option!")
      except ValueError:
         print("\nInvalid Input!")
   else:
      print("\nInvalid Choice!")
except ValueError:
   print("\nInvalid Input!")

Here is its sample run with user input 1 as a choice and myfile.txt as the name of the file:

python file handling complete program

Here is another sample run. This time, I've gone with the third option to check the append operation using the above program:

python file handling advance

And here is the last sample run. This time, I've done the cross-checking of the fourth choice to delete text from the file:

python file handling zero to hero

Note: To remove, rename, or create files or folders using Python, refer to the os module.

More Examples on File Handling

Python Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!