7 File Handling Operations in Python Explained with Programming Examples

7 File Handling Operations in Python Explained with Programming Examples

File handling is a very crucial concept in any programming. The file is used to store the text data which can be used by your program.

Want to learn how to create, open-read, and write in Python?

Here is a complete file-handling Python tutorial for you.

File Handling in Python

There are multiple operations to perform such as creating, reading, writing, and updating file content.

Let’s see how to do those file handling in Python with open() function with programming examples.

How to Create a File in Python?

We are using the open() built-in function to create a file.

open("myFile.txt", "w+")

This is the single open method that will create the file if it is not present.

To add content to the newly created file, you should open the file in write mode.

Two arguments are passed to the open() built-in function- the name of the file and the mode of the file (w+).

Here,

  • w – Create the file in write mode
  • + – Create a file if it’s not present in the current directory.

Note: The file will be created in the current directory (the directory where your Python code is running).

How to check if the file is present or not?

There are many techniques to check if the file is present or not. I have written a separate article explaining 3 ways to check file and directory existence in Python. Go through it.

How to open the File in Python?

You can use the same code as I have mentioned for creating a file.

open("myFile.txt", "r") as fObj

How to Read a File in Python?

First, open the file in reading mode “r” and then read the content from the file.

open("myFile.txt") as fObj
data = fObj.read()
print(data)

All the file contents will be saved in a single string object.

You can also use the “with” statement with an open file.

with open("myFile.txt") as fObj:
  data = fObj.read()
  print(data)

There are multiple benefits of using the “with” statement. We will see the benefits in the later part of this tutorial.

Nowadays it has become standard practice to open files using “with”.

How to Read Line-by-Line a File into a List?

Rather than reading complete file text in a single string object, what if you want to read the file line-by-line?

with open("myFile.txt") as fObj:
    liData = fObj.readlines()
    print(liData)

Each line in the file will be saved as one element in the list. So the size of the list will be the same as the number of lines in the file.

Reading a file in the list is very important when you want to manipulate the text in each line of the file. After reading the file content in the list, you just need to loop over each element in the list and perform your desired operation.

Python provides multiple list operations which makes your work associated with the file operation even easier.

How to Write a File in Python?

Two operations. First, open the file and then write the text content in it.

The file object has a write() method associated with it to write the text in the file.

with open("myFile.txt", 'a+') as fOut:
    fOut.write("my data to add."+'\n')

Here,

  • We are opening the file in “a+” mode so that, it will append the new content at the end of the file.
  • The “\n” character adds the text in a new line.

How to Close a File in Python?

It is always good practice to close the file after using it.

Python code to close and delete the file object if you are not performing any file operation further.

open("myFile.txt", "r") as fObj
#perform file operations
fObj.close()

Otherwise,

Use the “with” statement while opening the file. You don’t need to close the file object explicitly. As soon as the pointer goes out of the “with” statement block, the file object closes.

with open("myFile.txt", "r") as fObj:
    #perform file operations
    pass
#file is closed automatically

How to Delete File in Python?

Many times you need to delete the file instead of closing it.

If you try to delete the file which is not present, it will throw an I/O error.

Always check the file’s existence before deleting the file.

If the file is present, delete it.

import os
#delete file if it exists.
if os.path.exists("yourFile.txt"):
    os.remove("yourFile.txt")

The “path” and “remove” objects are described in the os module. So, you have to import the “os” module.

What are the different File Modes in Python?

There are multiple modes to open the file.

  • “r” mode:
    Open the file in reading mode. The pointer will be assigned at the beginning of the file. It will throw an error if the file does not exist.
  • “r+” mode:
    Open the file for reading and writing. The pointer will be assigned at the beginning of the file to read and write a file. It will throw an I/O error if the file does not exist.
  • “w” mode:
    Open the file in write mode. The pointer will be assigned at the beginning of the file and it will overwrite all the contents in the file.
  • “w+” mode:
    Open the file in read-write mode. All the data in the existing file will be truncated (delete and throw away) and overwritten.
  • “a” mode:
    Open the file in append mode. Instead of overwriting original content, in this mode, you can append the new content at the end of the file. If the file is not present, a new file will be created with the file name mentioned.
  • “a+” mode:
    Open the file in append mode. If the file does not exist, it will create a new file. It will append the new content at the end.  The existing content in the file will be intact.

As we can use both ‘r+’ and ‘w+’ modes are used for reading and writing a file, they are more confusing. But there is a catch. Read the difference between ‘r+’ and ‘w+’ mode in Python.

What is the default file mode?

If you don’t mention the file mode while opening the file, ‘r’ will be the default file mode

Best Practices for File Handling

1. Assign File Name to the Variable:

If you are reading and writing files multiple times, always create the variable for the file name. So you don’t need to assign file names every time in your program.

FILE_EMP = "empFile.txt"
with open(FILE_EMP) as fEmp: 
    liEmp = fEmp.readlines()

Even in the future if you need to change the file name, you just have to change the new file name in a variable. Otherwise, you have to update the text file everywhere you have used throughout your project. It’s time-consuming and not good practice.

2. Choose the Right Mode to Read, Write, or Append File

If you don’t want your program to write the file, always open the file only for reading.

The opening file in write mode will erase the original content in the file and will add new content. If you want your program to append the new content at the end of the file, always open a file in append mode.

3. Closing file object after using it. 

Otherwise, it is always a good choice to use the “with” statement while opening the file.

Coding Practice for File Handling in Python

You can not learn all these file operations without writing code. So here are some of the problems you can practice and learn file handling.

1. Write a Python program to remove all the duplicate lines from the file.

Hint: Read the file line-by-line in the list and find all the unique elements in the list. Write back all the content from the list in the file.

2. Write a Python program to randomly select any line from the file.

Hint: Read the file line-by-line in the list and randomly select elements from the list.

3. Write a Python program to add a given line to a file if it is not already there.

Hint: Read the line-by-line file into the list. Search if the given text is present. If it is not there, append the new content inside the file as a new line.

4. Write a Python program to find the longest line in the file.

Hint: The hint mentioned in the above three problems is sufficient to solve this problem as well.

Submit your code. I will publish your program on our portal.

Conclusion

This is all about a complete tutorial for file handling in Python. You have learned to create, to open, to read, and to write a text file. If you find any difficulty while handling the file or Python code mentioned in this tutorial, write in the comment.

For further, explore reading and writing CSV files in Python.

Happy Pythoning!

2 Comments

  1. When I am trying to read contents from my file,the single set of 2 statements is getting printed 5 times. Please help

Leave a Reply

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