Python File Handling

This article is created to cover all the topics of file handling along with example programs and its respective sample runs or outputs. Therefore, the tutorial on file handling here, is designed to make you feel like, from ground to top.

File handling is one of the hot topic of Python. Because, sometime we need to process the file using our Python program, to insert, update, or delete the information in/from the file.

The most used function in file handling is open(). Because every time to perform any operation on the file, we need to open the file first, and this function is used to open the file.

Note - Based on the opening modes, the file gets opened for the purpose of reading, writing, appending etc.

What is the Need of File Handling in Python ?

File handling is an important part while creating web applications using Python. There, most of the time, you need to store data in the form of files. The data may be some textual information, images, videos etc.

List of Methods used in File Handling

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

Other methods than these four, comes under the advance topic of file handling. I've covered both basic and advance version of file handling in this tutorial. So let me first describe those important methods, that plays the key role while handling the file in Python:

  • open() - used to open the file.
  • readable() - used to check whether the file can be read or not.
  • readline() - used to read a single (first) line from the file. Each time we use this function, the next line will get returned.
  • readlines() - used to read the whole content of file in the form of lines, where each line returned as element of list.
  • read() - used to read the whole content of file at once.
  • writable() - used to check whether the file is writable or not.
  • write() - used to write string to the file.
  • writelines() - used to write multiple strings to the file at once, where each string must be as element of the list.
  • close() - used to close the linkage of file from the program using the file object or handler.
  • seek() - used to move the object of the file handler in the file stream.
  • tell() - used to find the current position of the file handler in the file stream.

List of Important File Opening Modes

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

  • r - This mode is used for read only.
  • w - This mode is used for write only. If file exists, previous content will get deleted. If file does not exist, then a new file will get created.
  • a - Same as w but previous content will not get deleted. Used to append the content to the file.

Basics of File Handling in Python

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

  • opening a file
  • creating a file
  • writing to a file
  • reading a file
  • closing the file

Let's start with the first one, that 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, above file is opened in r or reading 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 told, all the modes along with these modes are described in open() function. For 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 where your Python's source code is getting saved. And the output produced by above program using its second statement will be:

python file handling

Since in my case, I'm saving my Python source code or the above program is saved in the directory say C:\Users\DEV\codescracker, therefore inside this, the file is created. Here is the snapshot of the directory along with newly created file using above program's sample run:

python file input output

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

Python File Write Operation

Since the file is created using above program. Therefore, it's time to write 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 say 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 say The content is written in the file. will get printed on the output console. Here is the snapshot of the sample output produced by above program:

python file handling programs

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

file handling in python

Python File Read Operation

As the file is created, also some content was written to the file using previous programs. Therefore it is the time to read the content from file. So the program given below opens the same file in reading mode using r, to read the content available in it:

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

The output produced by above program will be the text available in the file myfile.txt. Here is the snapshot shows 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 insertion of newline.

Python File Close Operation

After performing the operation such as read, write, update etc. to/from the file, we need to close the linkage of 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 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())

Now this time, the output produced by above program will be:

python file handling close file

That is, the code file_handler.read() inside the print() function raises an exception named ValueError saying I/O operation on closed file. or we can not perform input/output operation 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.")

Now the output will be the manual message that I've provided after catching the exception and putting the manual error message inside the except block. 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 of File Handling in Python

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

Create a File only if that File does not Exist

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

Because the file content will get deleted, so we may lost some important data. Therefore, we need to check whether the file that we're going to create, is already exists or not. If not, then only, we 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 exists. Otherwise, returns an error, i.e. FileExistsError.

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

python file handling create file if not exist

You can check the content of file myfile.txt. Everything will be untouched using the above program. Here is another sample run with user input yourfile.txt as name of 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 Whether a File is Writable or Not

Before writing content to a file, it is a 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 following user inputs:

  • myfile.txt as name of file
  • 2 as choice to write line by line
  • 3 as number of lines to write
  • This is the first line., This is the second line., and This is the third line. as three lines to write.

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

python file handling write file if writable

In above program, the statement:

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 allows, or the permission is not allowed.

Check Whether a File is Readable or Not

This program is similar to previous. 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 the 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, 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 basic section of file handling in Python, I've covered the topic, 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 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 appending and reading mode both. And the seek() is used to move the position of file object or handler in the file stream. Because I've used seek(0), therefore 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 same as of previous program. The only difference is instead of opening the file in both reading and appending mode, I've opened 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 file, instead of using seek() to move the handler at beginning to read the content. You can follow any way to do the job. But I recommend to go with second for beginner, otherwise first one is better.

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 using the new text. Let's see how. Here is a program 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 its sample run with user input myfile.txt, line as text to search, string as text to replace and finally y as choice to display the new content of file after performing 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 the things, along with handling of all errors. Do concentrate on the program and its sample run. Trust me, after understanding this program, you'll feel must 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 choice, and myfile.txt as name of 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 above program:

python file handling advance

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

python file handling zero to hero

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

More Examples on File Handling

Python Online Test


« Previous Tutorial Next Tutorial »