File Handling in Python

Tutorial Playlist

Understanding file handling in Python is crucial for managing data efficiently. Python provides various built-in functions that allow programmers to work with files easily, making operations like reading, writing, updating, and deleting data simple. It plays an important role when storing information permanently and accessing it whenever needed. In this tutorial, you will explore different file operations, their uses, and best practices to be followed to efficiently handle the files in Python.

Table of Contents:

What is File Handling?

File handling refers to creating, deleting, updating, reading, and closing files. In Python, we have some built-in methods for handling files. Files are stored on disk, and Python provides an efficient way to interact with the files and manage them.

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

Why is File Handling Important?

      • Ensures data persistence: Data that is saved and stored in a file remains the same even after the program has stopped running.
      • Helps in handling large amounts of data: It helps in making the process of reading, writing, and processing large data easier.
      • Allows programs to share data: Different applications can access and exchange information through files.
      • Automates tasks: Saves time by handling some repetitive tasks like logging data, saving reports, or backing up information.
      • Keeps data organized: Helps in storing the information in a more structured manner, which helps in making it easier to access and manage the data.

File Modes in Python

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

Mode Description
r (Read mode) It opens the file for reading only if it exists.
w (Write mode) It opens the file for writing, creating a new file if it does not exist. If the file exists, then it will overwrite it.
a (Append mode) It adds the data to the file at the end without removing or modifying the existing data.
x (Exclusive creation) It creates a new file and opens it for writing. If the file already exists, then it will raise an error.
b (Binary mode) It is used to read and write binary files like 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 reading and writing If the file does not exist, it gives an error. Then gives an error if the file does not exist.
a+  (Append and read mode) It opens a file for appending along with reading and will create a new file if it does not exist.

File Handling Operations in Python

File handling operations in Python allow you to manage files efficiently for storing and organizing data. It enables interaction with files to perform various operations as needed. Python provides built-in functions that help in simplifying file management. Now, let us explore the different file-handling operations in Python in detail to understand how to manage and work with files efficiently.

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. For opening a file in Python, there is a built-in function open(), which takes two arguments: the 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.

2. Writing into a File in Python

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 ‘’ mode to write anything in the file.

Using the write() method in Python

This method is used to write text in the file.

Example:

Python

Output:

Explanation: In the above code, we open a file named “sample.txt” in write mode (“w”) using the open() function. The write() method here helps in adding the text “Hello, Welcome to Intellipaat!” to the file. After writing, we open the same file in read mode (“r”) and use the read() method to display its content.

Using the writelines() method in Python

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

Example:

Python

Output:

Explanation: Here, in this example, “intellipaat_courses.txt” is created and writes three course names using writelines(). If the file exists, it overwrites the

Shape Your Career as a Python Developer
Grow with Our Python Training
quiz-icon

3. Reading a File in Python

The read() method is used to read data from a file. To read the file, we have to open the file in read mode(r). We can read data from a file in Python in three different ways, 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.

Using the read() method in Python

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

Example:

Python

Output:

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

Using readline() method in Python

This method reads the file line by line.

Example:

Python

Output:

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

Using readlines() method in Python

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

Example:

Python

Output:

Explanation: Here, we opened intellipaat_courses.txt, used readlines() to store all lines in a list, and printed them efficiently without extra spaces.

4. Closing a File in Python

You can use the close() function to close an opened file in Python. We must close the file after opening it to release all the resources. This function also ensures that the changes made to the files must be saved before closing the file.

Syntax:
file = open(‘file.txt’, ‘r’)
file.close() # Close the file

Example:

Python

Output:

Explanation: Here, the intellipaat_courses.txt file is opened, and  “Python Files” is written to it, and then ensured that the file is closed properly, printing “File closed !!” after the file is closed.

  • Using “with” Statement for Automatic File Closing

The ‘with’ statement is used to automatically close the file. It is the best practice to close the file in Python. It ensures that the file is closed after all the operations are completed, which reduces the risk of corruption of the file.

Example:

Python

Output:

Explanation: Here, the file named intellipaat_courses.txt is opened. The data is read from the file, and the file is closed automatically after printing the data.

5. Deleting a File in Python

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

Example:

Python

Output:

Explanation: Here, the file named intellipaat_courses.txt is deleted using the os.remove() function.

6. Copying a File in Python

To copy a file, use the shutil module, which provides efficient file operations.

Example:

Python

Output:

Explanation: The file is opened in write mode (“w”) and modified using a try-finally block to ensure closure. The shutil.copy() method is used to copy the file to copied_courses.txt.

7. Handling the Binary Files in Python

While reading binary files like images, PDFs, or any executable files, we can use the “rb” (read binary) or “wb” (write binary) mode.

Example: Writing & Reading a Binary File

Python

Output:

Explanation: A binary file binary_file.bin is created and written using “wb” mode. The file is read using “rb” mode, and the binary content is printed, which shows b’Hello’ as the output.

8. Renaming a File in Python

To rename a file in Python, we use the os.rename() function that helps in overwriting the existing filename with a new one whenever needed in a simpler manner.

Example: Creating & Renaming a File

Python

Output:

Explanation: The file sample_file.txt is created and written using “w” mode. The os.rename() function renames sample_file.txt to renamed_sample.txt.

9. Checking if a File Exists in Python

Checking whether a file exists is very important when working with various files. In Python, we use the os.path.exists() method from the os module to check the existence of the file.

Example:

Python

Output:

Explanation: The os.path.exists() method checks if intellipaat_courses.txt exists. If the file is present, it prints “File exists!”.

10. Appending to a File in Python

When we need to add some data to a file instead of rewriting the whole data again, we can append data to a file by using the ‘a’ mode with the open() function. This mode helps in adding new content at the end of the file without deleting existing data.

Example:

Python

Output:

Explanation: The os.path.exists() method checks if intellipaat_courses.txt exists. If the file is present, it prints “File exists!”. Then, the ‘a’ mode in open() appends “Full Stack” to the file without deleting the already existing data and displays it.

Alternate Methods of File Handling in Python

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

Alternate Methods of File Handling in Python

Method Description
flush() Clears the internal buffer and writes data to the file immediately.
seek(offset,from=SEEK_SET) Moves the file offset (pointer) to a specific position (start, current, or end).
tell() It returns the current file location.
writable() Check if the file can be written, then return True or False based on the condition.
readable() Returns True if the file stream can be read, else returns False.
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:

  1. Data Persistence: Files store the data permanently, which ensures that the data is accessible even after the completion of the execution.
  2. Data Manipulation: Python allows users to perform file reading and writing and file update operations with high efficiency.
  3. Data Exchange: Python supports various file formats, including text files, CSV, JSON, and binary files, which enables simple data management procedures.
  4. Versatile: Python handles different file types, like text, CSV, JSON, and binary files, which allows easy manipulation of the data.
  5. Integration: File handling helps in integrating your external data sources, such as databases, which allow you 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:

  1. Security: There are chances of the files getting easily updated, written, and copied from an external source, which would be a security risk. So there is a need to protect the file efficiently.
  2. Performance: Operations involving files are slower than data management from memory.
  3. Error handling: Users need to handle various errors during file handling because missing files or incorrect permissions, or unexpected failures could occur.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

In this tutorial, we covered essential file-handling operations like reading, writing, appending, and closing files, which are very important for efficiently handling the data. Python provides many built-in functions for performing these operations. While these are the basic fundamental concepts, Python also offers advanced techniques and libraries for specific use cases. If you’re eager to master them and take your skills to the next level, join our trending Python Course and also explore basic Python Interview Questions prepared by industry experts to improve your preparation.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort Starts on: 19th Apr 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.