File Handling in Python

UpComing SoftWare Training Demos

🚀 *Playwright With AI Testing Demo In Telugu*
🗓️ *Date:* 28 Oct2026, 08:00 PM IST
📝 *Register Now!:*
https://www.vlrt.in/3r
👥 *Join WA Community:*
https://www.vlrt.in/3w
💡 *Course Content:*
https://www.vlrt.in/3c
▶️ *Demo Videos:*
https://www.vlrt.in/3v

🚀 *Gen AI Engineer (Production Focused)*
🗓️ *Date:* 29th Oct 2026, 06:00PM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 28th Oct 2026, 10:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

File Handling in Python

File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently.

Basic File Operations

1. Opening a File

Use the open() function to open a file. It returns a file object.

python

# Syntax: open(filename, mode)
file = open("example.txt", "r")  # Open for reading

2. File Modes

  • 'r' – Read (default)
  • 'w' – Write (creates new file or truncates existing)
  • 'a' – Append
  • 'x' – Exclusive creation (fails if file exists)
  • 'b' – Binary mode
  • 't' – Text mode (default)
  • '+' – Read and write

3. Reading Files

python

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

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

# Read specific number of characters
with open("example.txt", "r") as file:
    chunk = file.read(100)  # Read first 100 characters

# Read all lines into a list
with open("example.txt", "r") as file:
    lines = file.readlines()

4. Writing to Files

python

# Write to file (overwrites existing content)
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.\n")

# Append to file
with open("example.txt", "a") as file:
    file.write("This line is appended.\n")

5. The with Statement

The with statement automatically handles file closing, even if exceptions occur.

python

# Recommended way
with open("example.txt", "r") as file:
    content = file.read()
# File is automatically closed here

# Traditional way (not recommended)
file = open("example.txt", "r")
try:
    content = file.read()
finally:
    file.close()

Practical Examples

Example 1: Reading and Processing Data

python

# Count lines in a file
with open("data.txt", "r") as file:
    line_count = 0
    for line in file:
        line_count += 1
    print(f"Total lines: {line_count}")

# Process CSV-like data
with open("data.csv", "r") as file:
    headers = file.readline().strip().split(',')
    for line in file:
        values = line.strip().split(',')
        # Process each row
        print(dict(zip(headers, values)))

Example 2: Writing Structured Data

python

# Write multiple lines
data = ["Line 1", "Line 2", "Line 3"]

with open("output.txt", "w") as file:
    for line in data:
        file.write(line + "\n")

# Write formatted data
users = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30}
]

with open("users.txt", "w") as file:
    for user in users:
        file.write(f"{user['name']},{user['age']}\n")

Example 3: File Copy

python

def copy_file(source, destination):
    try:
        with open(source, "rb") as src, open(destination, "wb") as dest:
            dest.write(src.read())
        print("File copied successfully!")
    except FileNotFoundError:
        print("Source file not found!")
    except Exception as e:
        print(f"Error: {e}")

copy_file("source.txt", "copy.txt")

Error Handling

python

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")
except PermissionError:
    print("Permission denied!")
except Exception as e:
    print(f"An error occurred: {e}")

Working with Binary Files

python

# Read binary file (like images)
with open("image.jpg", "rb") as file:
    binary_data = file.read()

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

File Position and Seeking

python

with open("example.txt", "r+") as file:
    # Get current position
    position = file.tell()
    print(f"Current position: {position}")
    
    # Read first 10 characters
    content = file.read(10)
    
    # Move to beginning
    file.seek(0)
    
    # Write at beginning
    file.write("START")

Best Practices

  1. Always use the with statement for automatic resource management
  2. Handle exceptions when working with files
  3. Use appropriate modes for your operations
  4. Close files explicitly if not using with
  5. Be careful with 'w' mode as it overwrites existing content
  6. Use binary mode for non-text files

File handling in Python is straightforward and powerful, making it easy to work with various file formats and perform complex file operations.

Python open() Method and File Modes

The open() Method

The open() function is used to open files and returns a file object.

Syntax:

python

open(filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

File Modes with Examples

1. Read Mode ('r')

Opens a file for reading (text mode).

Example 1: Basic Reading

python

# Create a sample file first
with open("sample.txt", "w") as f:
    f.write("Hello World!\nPython File Handling")

# Read the file
with open("sample.txt", "r") as file:
    content = file.read()
    print("File content:")
    print(content)

Example 2: Reading Line by Line

python

with open("sample.txt", "r") as file:
    print("Reading line by line:")
    for i, line in enumerate(file, 1):
        print(f"Line {i}: {line.strip()}")

2. Write Mode ('w')

Creates a new file or truncates existing file for writing.

Example 1: Creating New File

python

# Write to a new file (creates if doesn't exist)
with open("new_file.txt", "w") as file:
    file.write("This is line 1\n")
    file.write("This is line 2\n")
    print("File created and written successfully!")

# Verify content
with open("new_file.txt", "r") as file:
    print("Content:", file.read())

Example 2: Overwriting Existing File

python

# Original content
with open("data.txt", "w") as file:
    file.write("Original content")

# Overwrite the file
with open("data.txt", "w") as file:
    file.write("New content - old content is gone!")

# Check result
with open("data.txt", "r") as file:
    print("After overwrite:", file.read())

3. Append Mode ('a')

Opens file for appending, creates if doesn’t exist.

Example 1: Appending to File

python

# Initial content
with open("log.txt", "w") as file:
    file.write("Log started\n")

# Append new entries
with open("log.txt", "a") as file:
    file.write("Entry 1: User logged in\n")
    file.write("Entry 2: File uploaded\n")

# Check final content
with open("log.txt", "r") as file:
    print("Log content:")
    print(file.read())

Example 2: Appending Multiple Times

python

# Append data at different times
events = ["Event 1: Started", "Event 2: Processing", "Event 3: Completed"]

for event in events:
    with open("events.log", "a") as file:
        file.write(f"{event}\n")

# Read all events
with open("events.log", "r") as file:
    print("All events:")
    print(file.read())

4. Exclusive Creation Mode ('x')

Creates file exclusively, fails if file exists.

Example 1: Successful Creation

python

try:
    with open("unique_file.txt", "x") as file:
        file.write("This file was created exclusively!")
    print("File created successfully with 'x' mode")
except FileExistsError:
    print("File already exists!")

Example 2: Handling Existing File

python

# First create a file
with open("test_x.txt", "w") as file:
    file.write("Existing content")

# Try to create with 'x' mode
try:
    with open("test_x.txt", "x") as file:
        file.write("This won't work")
except FileExistsError as e:
    print(f"Error: {e}")
    print("File already exists, cannot create exclusively")

5. Binary Mode ('b')

Used for non-text files (images, executables, etc.).

Example 1: Reading Binary File

python

# First create a simple binary file
with open("binary_data.bin", "wb") as file:
    file.write(b'\x48\x65\x6C\x6C\x6F')  # Hello in bytes

# Read binary file
with open("binary_data.bin", "rb") as file:
    binary_content = file.read()
    print("Binary content:", binary_content)
    print("As string:", binary_content.decode('utf-8'))

Example 2: Copying Binary File

python

# Create source binary file
with open("source.bin", "wb") as file:
    file.write(bytes(range(10)))  # Write bytes 0-9

# Copy binary file
with open("source.bin", "rb") as src, open("copy.bin", "wb") as dest:
    dest.write(src.read())

print("Binary file copied successfully!")

6. Read/Write Mode ('+')

Opens file for both reading and writing.

Example 1: Read and Write ('r+')

python

# Create file with initial content
with open("data_rw.txt", "w") as file:
    file.write("Line 1\nLine 2\nLine 3")

# Read and modify
with open("data_rw.txt", "r+") as file:
    content = file.read()
    print("Original:", repr(content))
    
    file.seek(0)  # Go to beginning
    file.write("Modified Line 1\n")
    
    file.seek(0)
    print("After modification:", file.read())

Example 2: Write and Read ('w+')

python

with open("data_wr.txt", "w+") as file:
    # Write first
    file.write("Initial content\n")
    file.write("Second line\n")
    
    # Then read
    file.seek(0)
    content = file.read()
    print("Content after write+read:")
    print(content)

7. Append and Read ('a+')

Opens file for appending and reading.

Example 1: Append and Read

python

with open("data_ar.txt", "a+") as file:
    # Append new content
    file.write("New appended line\n")
    
    # Read what was written
    file.seek(0)
    content = file.read()
    print("All content after append:")
    print(content)

Example 2: Multiple Operations

python

with open("log_ar.txt", "a+") as file:
    # Read existing content first
    file.seek(0)
    old_content = file.read()
    print("Existing content:", repr(old_content))
    
    # Append new content
    file.write(f"New entry at position {file.tell()}\n")
    
    # Read everything again
    file.seek(0)
    print("Final content:")
    print(file.read())

Mode Combinations Table

ModeDescriptionFile Position
'r'Read (default)Beginning
'r+'Read + WriteBeginning
'w'Write (truncate)Beginning
'w+'Write + Read (truncate)Beginning
'a'AppendEnd
'a+'Append + ReadEnd
'x'Exclusive creationBeginning
'x+'Exclusive creation + Read/WriteBeginning
'rb'Read binaryBeginning
'wb'Write binaryBeginning

Important Notes

  1. Always use with statement for automatic file closing
  2. Text mode ('t') is default – handles line endings automatically
  3. Binary mode ('b') preserves exact byte content
  4. File position matters when using read/write modes together
  5. Use seek() to navigate within the file
  6. Handle exceptions for file operations

These examples demonstrate the power and flexibility of Python’s file handling capabilities!

Similar Posts

  • Challenge Summary: Inheritance – Polygon and Triangle Classes

    Challenge Summary: Inheritance – Polygon and Triangle Classes Objective: Create two classes where Triangle inherits from Polygon and calculates area using Heron’s formula. 1. Polygon Class (Base Class) Properties: Methods: __init__(self, num_sides, *sides) python class Polygon: def __init__(self, num_sides, *sides): self.number_of_sides = num_sides self.sides = list(sides) 2. Triangle Class (Derived Class) Inheritance: Methods: __init__(self, *sides) area(self) python import math…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • install Python, idle, Install pycharm

    Step 1: Download Python Step 2: Install Python Windows macOS Linux (Debian/Ubuntu) Open Terminal and run: bash Copy Download sudo apt update && sudo apt install python3 python3-pip For Fedora/CentOS: bash Copy Download sudo dnf install python3 python3-pip Step 3: Verify Installation Open Command Prompt (Windows) or Terminal (macOS/Linux) and run: bash Copy Download python3 –version # Should show…

  • Class 10 String Comparison ,Bitwise Operators,Chaining Comparisons

    String Comparison with Relational Operators in Python 💬⚖️ In Python, you can compare strings using relational operators (<, <=, >, >=, ==, !=). These comparisons are based on lexicographical (dictionary) order, which uses the Unicode code points of the characters. 📖 How String Comparison Works 🤔 Examples 💡 Python Important Notes 📌 String comparison is…

Leave a Reply

Your email address will not be published. Required fields are marked *