Table of Contents


What is File Handling?

File handling in Python allows you to manage and process data stored in files, whether they are text or binary. This is essential for tasks like reading data from files, storing results, or logging application activities.


Types of Files in Python

Python supports working with two main types of files:

  1. Text Files: Contains plain text, readable by humans. Example: .txt, .csv.
  2. Binary Files: Contains data in binary format, readable by machines. Example: .jpg, .exe.

Opening and Closing Files

To work with files in Python, you first need to open them. After the operation, you should always close the file to free resources.

Syntax:

file = open("filename", "mode")  # Open the file
file.close()  # Close the file

Example:

file = open("example.txt", "r")
# Perform operations
file.close()

File Modes

When opening a file, you specify the mode:

Mode Description
'r' Read-only mode (default).
'w' Write mode (overwrites file).
'a' Append mode (adds to file).
'rb' Read-only binary mode.
'wb' Write binary mode.
'r+' Read and write mode.

Reading from a File

You can read data using methods like read(), readline(), or readlines().

Example:

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

# Read entire content
content = file.read()
print(content)

# Read line by line
file.seek(0)  # Reset pointer
for line in file:
    print(line)

file.close()

Writing to a File

Use the write() method to write data to a file. If the file doesn’t exist, it will be created.

Example:

file = open("example.txt", "w")
file.write("Hello, AI Noob Nook!\n")
file.close()

Appending to a File

Use the a mode to add new content without overwriting existing data.

Example:

file = open("example.txt", "a")
file.write("Let's learn Python file handling.\n")
file.close()

Working with Binary Files

Binary files store data in binary format. Use ‘rb’ or ‘wb’ for reading or writing.

Example:

# Writing binary data
with open("binaryfile.bin", "wb") as file:
    file.write(b'\x48\x65\x6c\x6c\x6f')

# Reading binary data
with open("binaryfile.bin", "rb") as file:
    data = file.read()
    print(data)

Best Practices for File Handling

1. Use with Statement: Automatically closes files after operation.

with open("example.txt", "r") as file:
    content = file.read()

2. Handle Exceptions: Use try-except blocks to handle errors

try:
    with open("example.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")

Quick Practice

  1. Write a program to read a file and print the number of lines, words, and characters.
  2. Create a file and write a list of numbers to it, then read and calculate their sum.
  3. Write a program to copy a binary file.

Wrap-Up

Today, we learned about:

  • Opening and closing files.
  • Different modes for file operations.
  • Reading, writing, and appending files.
  • Handling binary data.
  • Best practices for file handling.
  • Mastering file handling is crucial for working with real-world data. Practice these examples and explore how Python simplifies file management.

Day 5: Exploring Data Structures in Python
Back to Home
Day 7: Error and Exception Handling in Python – Build Resilient Code