File Handling in Python

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

  • 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 =…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

Leave a Reply

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