Python File Handling – Read, Write, Open & Manage Files

Introduction

File handling is one of the most important concepts in Python programming. In real-world applications, data is often stored in files rather than being entered manually every time a program runs. Python provides built-in functions and methods that make it easy to create, read, write, update, and delete files.

Whether you are building a logging system, storing user information, managing reports, or processing large datasets, file handling plays a crucial role. Python supports various file formats such as text files, CSV files, JSON files, and binary files.

What is Python File Handling?

Python File Handling refers to the process of working with files on a computer. It allows programmers to:

  • Create files
  • Open files
  • Read data from files
  • Write data to files
  • Append data to files
  • Close files
  • Delete files

Python uses the built-in open() function to work with files.

A file can be opened in different modes depending on the operation you want to perform.

Common File Modes

Mode Description
r Read mode (default)
w Write mode (creates a new file if it doesn’t exist)
a Append mode
x Create a file
rb Read binary file
wb Write binary file
r+ Read and write

Syntax

The basic syntax for opening a file is:


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

Parameters

  • filename.txt → Name of the file.
  • mode → Specifies how the file should be opened.

Example:


file = open("data.txt", "r")

After completing operations, close the file:


file.close()

Reading Files in Python

Python provides several methods for reading file contents.

read()

Reads the entire file.


file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

Output:

Hello World
Welcome to Python

readline()

Reads one line at a time.


file = open("data.txt", "r")
print(file.readline())
file.close()

Output:

Hello World

readlines()

Returns all lines as a list.


file = open("data.txt", "r")
lines = file.readlines()
print(lines)
file.close()

Output:

[‘Hello World\n’, ‘Welcome to Python’]

Writing Files in Python

The w mode is used to write data to a file.


file = open("data.txt", "w")
file.write("Python File Handling")
file.close()

Output:

Python File Handling

Important: If the file already exists, the previous content will be overwritten.

Appending Data

Use a mode to add content without deleting existing data.


file = open("data.txt", "a")
file.write("\nLearning Python")
file.close()

Output:

Python File Handling
Learning Python

Using the with Statement

Python provides the with statement which automatically closes files.

with open(“data.txt”, “r”) as file: content = file.read() print(content)

Benefits:

  • Cleaner code
  • Automatic file closing
  • Better memory management

Creating a New File

You can create a new file using x mode.


file = open("newfile.txt", "x")
file.close()

If the file already exists, Python raises an error.

Deleting a File

Python uses the os module to delete files.


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

Check before deleting:


import os
if os.path.exists("data.txt"):
    os.remove("data.txt")
else:
    print("File not found")

Working with Binary Files

Binary files are used for images, videos, PDFs, and other non-text data.

Writing Binary Data


file = open("sample.bin", "wb")
file.write(b"Hello")
file.close()

Reading Binary Data


file = open("sample.bin", "rb")
data = file.read()
print(data)
file.close()

Output:

b’Hello’

Example

The following example demonstrates reading and writing a file.


with open("students.txt", "w") as file:
    file.write("John\n")
    file.write("Alice\n")
    file.write("Bob\n")
with open("students.txt", "r") as file:
    print(file.read())

Output:

John
Alice
Bob

This example first creates a file and then reads its content.

Real-life Example

Imagine you are developing a student management system. Instead of storing student names in variables, you can save them in a file.


student_name = input("Enter student name: ")
with open("students.txt", "a") as file:
    file.write(student_name + "\n")
print("Student saved successfully.")

Common Mistakes

1. Forgetting to Close the File

Incorrect:


file = open("data.txt", "r")
print(file.read())

Correct:


file = open("data.txt", "r")
print(file.read())
file.close()

Or use:


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

2. Opening a Non-Existing File in Read Mode

Incorrect:


file = open("unknown.txt", "r")

Output:

FileNotFoundError

Correct:


import os
if os.path.exists("unknown.txt"):
    file = open("unknown.txt", "r")

3. Using Write Mode Accidentally

Incorrect:


file = open("data.txt", "w")
This removes existing content.

Correct:


file = open("data.txt", "a")

Use append mode if you want to keep previous data.

4. Using Incorrect File Paths

Incorrect:


open("myfile.txt", "r")

When the file is located in another folder.

Correct:


open("files/myfile.txt", "r")

5. Not Handling Exceptions

Incorrect:


open("files/myfile.txt", "r")

Correct:


try:
    file = open("data.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("File not found")

Conclusion

Python File Handling is a fundamental feature that enables programs to work with external files efficiently. Using the open() function, developers can read, write, append, and manage data stored in files. Understanding file modes, proper file closing techniques, and exception handling is essential for building reliable applications.

Python File Handling – Interview Questions

Q 1: What is file handling in Python?
Ans: File handling allows reading from and writing to files using Python code
Q 2: Which function opens a file in Python?
Ans: The open() function is used to open files.
Q 3: What are common file modes in Python?
Ans: 'r' for read, 'w' for write, 'a' for append, and 'rb' for binary read.
Q 4: How do you close a file?
Ans: Using the close() method or the with statement automatically.
Q 5: Why is file handling important?
Ans: It allows persistent storage of data and reading/writing operations.

Related Python Tutorials