File Handling in Python

Tutorial Playlist

File handling refers to the process of playing with files that involve processes like creating, updating, opening, and deleting files. In this tutorial, we will learn file handling and file manipulation in Python.

Table of Content

What is File Handling

What is File Handling?

File handling refers to creating, deleting, updating, reading, and closing the files. In Python, we have some built-in methods for file handling. Files are stored on disk, and Python gives us a way to interact with those files.

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

  1. Text files
  2. Binary files

Let’s learn operations in file handling:

1. Opening a File in Python

To perform any operation on the files in Python, the first step is to open the file. Only then, will we be able to proceed with the next steps, and for opening a file in Python, there is a built-in function open(), that takes two arguments, file name and the mode in which we want to open the file.

Syntax to open a file:

file = open("filename", "mode")

Here, the filename is the name of the file, and mode is the mode of the file in which we want to open the file.

File Modes in Python

Let’s learn the mode of the files in which we can open the file:

Mode Description
r Read mode – Opens the file for reading. The file must exist.
w Write mode – Opens the file for writing, creating a new file if it does not exist. If the file exists, it overwrites the file.
a Append mode – Opens the file for appending. Data written to the file is added at the end without removing existing data.
x Exclusive creation– Creates a new file and opens it for writing. If the file already exists, it raises an error.
b Binary mode – Used for reading or writing binary files (e.g., images).
t  Text mode – This is the default mode. Text files are read and written in string format.
r+ Read and Write mode – it opens a file for writing and then gives an error if the file does not exist.
w+ Write and read mode – it opens a file for both writing and reading, it will create a new file if it does not exist, and truncate the content of the file if it already exists.
a+ Append and read mode – it opens a file for appending and reading, it will create a new file if it does not exist.

2. Writing into a File

If we want to write into a file, we have to use the function file.write(). It will create a new file if it does not exist, and if it does, it will delete all the content and update the new one.  We have to use ‘w’mode to write anything in the file.

Example: Using the write() method

Code:

file = open("hello.txt", "w")
file.write("Intellipaat")
file.close()

Output:

Intellipaat

Explanation:

here we have opened the file with the file name(hello.txt) in ‘w’ mode means writing mode, and writing the content, if this file does not exist, it will be created, and the content will be added to that file, and if the file exists, the string ”intellipaat” is overwritten into the file.

Example: using the writelines() method

This method is used to write multiple lines in the file.

Code:

languages = ["ReactJs\n", "NodeJs\n", "Javascript\n"]
with open("hello.txt", "w") as file:
file.writelines(languages)
print ("Content added !!")

Output:

Content added

Explanation:

Here we are writing multiple lines into the file, with the help of writelines() function.

3. Reading a File

The read() method is used to read data from a file. for reading the file we have to open the file in read mode(r). We can read data from a file in Python in three different methods, with these three functions:

  • read(): it will read the whole file
  • readline(): this function will read one line at a time
  • readlines(): this function will read all lines into a list.

Example: Using read() method

Suppose we have a file named hello.txt, and we want to read the data of the file, following code will help us to read the data from the file.

Code:

with open("hello.txt", "r") as file:
   data = file.read()
   print(data)

Output:

ReactJs, NodeJs, Javascript

Explanation: We have opened the file named hello.txt and read the file with read(), and printed the data.

Example: Using readline() method

This function helps us to read the file line by line.

Code:

with open("hello.txt", "r") as file:
   data = file.readline()
   while data:
      print(data, end='')
      data = file.readline()

Output:

“Hello”
“Intellipaat”

Explanation: if the file contains two or more line, then we will use this function to read the file.

Example: Using readlines() method

This function helps us to read all lines and put them into a list. Let’s

Code:

with open("example.txt", "r") as file:
   data = file.readlines()
   for line in data:
      print(line, end='')

Example:

“Hello”
“Intellipaat”

4. Closing a File

To close an opened file in Python, we have to use close() function, it is necessary to close the file after opening it to release all the resources. It also makes sure the changes made to the files must be saved before closing the file.

Syntax:

file = open('file.txt', 'r')
file.close()    # Close the file

Using “with” Statement for Automatic File Closing

‘with’ statement is used for automatically closing the file. It is the best practice to close the file in Python. It ensures that the file is automatically closed after all the operations completed even after there is an exception occurs. It also reduces the risk of file corruption and resource leakage.

Code:

with open("hello.txt", "r") as file:
   data = file.read()
    print(data)

Explanation: The above code will open the file named hello.txt. Read data from the file, and close the file automatically after printing the data.

Handling Exceptions When Closing a File

When dealing with file operations, it’s important to deal with exceptions while closing the file, this can be done by using a try-finally block that ensures that the file is closed properly.

Example:

try:
   file = open("hello.txt", "w")
   file.write("Hello World!")
finally:
   file.close()
   print ("File closed !!")

Output:

File Closed

5. Deleting a File in Python

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

Code:

import os
os.remove("hello.txt")

Checking if File Exists

Before deleting the file, we have to check whether the file exists or not to avoid getting an error. Below is the code that helps us to check file existence.

Example:

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

6. Other Methods of File Handling in Python

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

Other Methods of File Handling in Python

Method Description
flush() To flush the write buffer of the file stream
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
readable() It returns true Returns True if the file stream can be read from.
rename() It helps us to rename the file.

Advantages of File Handling in Python

Here are some of the advantages of file handling in Python:

  • Data Persistence: we can store data in files permanently, which remains available even after the program terminates.
  • Data Manipulation: Python provides a lot of built-in functions to read, write, and update files easily.
  • Data Exchange: Data can be shared among multiple sources with the help of file handling in Python.
  • Versatile: Python supports different file types like: text, CSV, JSON, and binary files, and allows us to manipulate the data easily.
  • Integration: with the help of file handling, we can integrate our external data sources: such as databases, API integration, and Web Services, and allow us to play with that data according to the project requirements.

Disadvantages of File Handling in Python

Here are some of the advantages of file handling in Python:

  • Security: it might be possible that the files are easily updated, written, and copied from an external source, which would be a security risk. So we have to protect the file efficiently.
  • Performance: reading and writing to files involve file access, which is comparatively slower than working with memory directly.
  • Error handling: file handling can fail for reasons like file not exist and permission issues. So it is irritating sometimes to use file handling in Python.

Conclusion

So far in this article, we have learned how to read, write, close, append, and open a file. there are a lot of in-built functions in Python for doing these operations. We have also learned exception handling in file handling. This tutorial has covered the fundamental concepts of file handling, but there are many more advanced techniques and libraries available in Python for specific use cases. If you’re eager to master them and take your skills to the next level, join our trending Python course today!”

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 1st Feb 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.