What is File Handling in Python?

File handling in Python allows you to interact with files to perform operations like reading, writing, and appending data. It is crucial for managing data storage, logging, and configuration files.

 

Opening Files in Python

Use the open() function to open a file. It requires the filename and mode.

File Modes:

ModeDescription
"r"Read mode (default). File must exist.
"w"Write mode. Creates a file or overwrites existing content.
"a"Append mode. Adds data to the end of the file.
"x"Create mode. Creates a file; fails if it exists.
"b"Binary mode (e.g., images, videos).
"t"Text mode (default).

Syntax:

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

Reading Files in Python

1. Reading the Entire File

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

2. Reading Line by Line

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # Removes trailing newline characters

3. Reading Specific Lines

with open("example.txt", "r") as file:
    lines = file.readlines()
    print(lines[0])  # Prints the first line

Writing to Files in Python

1. Writing New Content

with open("example.txt", "w") as file:
    file.write("Hello, World!\nThis is a test.")

Note: Existing content will be overwritten.

2. Appending to a File

with open("example.txt", "a") as file:
    file.write("\nAppending a new line.")

Working with Binary Files

Binary files handle non-text data like images or videos.

Example: Reading and Writing Binary Data

# Reading binary file
with open("image.jpg", "rb") as file:
    data = file.read()

# Writing binary file
with open("copy.jpg", "wb") as file:
    file.write(data)

File Handling Best Practices in Python

Use with Statement:

  • Automatically closes the file after the block ends.
with open("example.txt", "r") as file:
    content = file.read()

Handle File Exceptions:

  • Use try-except to handle missing or inaccessible files.
try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")

Avoid Hardcoding File Paths:

  • Use os or pathlib for portability.
from pathlib import Path
path = Path("example.txt")
if path.exists():
    print(path.read_text())

Checking File Properties

Use the os or pathlib module for file metadata.

Example:

import os

file_path = "example.txt"
if os.path.exists(file_path):
    print(f"File Size: {os.path.getsize(file_path)} bytes")
    print(f"File Name: {os.path.basename(file_path)}")
    print(f"Directory: {os.path.dirname(file_path)}")
else:
    print("File does not exist.")

Deleting Files

Example:

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted.")
else:
    print("File does not exist.")

Common File Operations

OperationExample Code
Check if file existsos.path.exists("example.txt")
Rename fileos.rename("old.txt", "new.txt")
Create directoryos.mkdir("new_folder")
Delete directoryos.rmdir("new_folder")
List directory filesos.listdir("path")

Practice Exercises

1. Writing User Input to a File

Write a program that takes user input and saves it to a file.

with open("user_data.txt", "w") as file:
    name = input("Enter your name: ")
    file.write(f"Name: {name}\n")

2. Counting Words in a File

Write a program that reads a file and counts the number of words.

with open("example.txt", "r") as file:
    content = file.read()
    words = content.split()
    print(f"Word count: {len(words)}")