Python File Handling

basic
Published

September 12, 2024

Opening and Closing Files

The method used file handling is the open() function. It takes the file path as the first argument and a mode as the second. Common modes include:

  • "r": Read (default)
  • "w": Write (overwrites existing file)
  • "a": Append (adds to the end of the file)
  • "x": Create (fails if the file already exists)
  • "b": Binary mode (for non-text files)
  • "t": Text mode (default)

It’s important to always close files using close() to ensure data is properly written and resources are released. However, using with open(...) as f: is the preferred method as it automatically handles closing the file, even if errors occur.

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


try:
    with open("output.txt", "w") as file:
        file.write("This is some text.\n")
        file.write("This is another line.")
except Exception as e:
    print(f"An error occurred: {e}")

try:
    with open("output.txt", "a") as file:
        file.write("\nThis is appended text.")
except Exception as e:
    print(f"An error occurred: {e}")

Reading Files

Python provides many ways to read file contents:

  • read(): Reads the entire file into a single string.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines into a list of strings.
with open("my_file.txt", "r") as file:
    # Read the entire file
    all_content = file.read()
    print(f"All content:\n{all_content}")

    file.seek(0) #reset the file pointer to the beginning

    # Read line by line
    line = file.readline()
    while line:
        print(f"Line: {line.strip()}")
        line = file.readline()


    file.seek(0) #reset the file pointer to the beginning

    #Read all lines into a list
    all_lines = file.readlines()
    print(f"All lines as list: {all_lines}")

Writing Files

Writing to a file involves using the write() method. Remember that "w" mode overwrites existing content, while "a" mode appends to the end.

data = ["Line 1\n", "Line 2\n", "Line 3"]

with open("new_file.txt", "w") as file:
    file.writelines(data) #Write a list of strings

with open("new_file.txt", "a") as file:
  file.write("This is appended on a new line.")

Working with Different File Types

Python handles various file types seamlessly. For binary files (like images or executables), use the "rb" (read binary) or "wb" (write binary) modes.

try:
    with open("image.jpg", "rb") as file:
        image_data = file.read()
        # Process image_data...
except FileNotFoundError:
    print("Image file not found.")

Handling Exceptions

File operations can throw exceptions (like FileNotFoundError or IOError). Always use try...except blocks to handle potential errors gracefully.

try:
    with open("nonexistent_file.txt", "r") as file:
        contents = file.read()
except FileNotFoundError:
    print("File not found.  Check the file path.")
except Exception as e:
    print(f"An error occurred: {e}")

File Paths and Directories

When working with files, understanding file paths is essential. You can use absolute paths (starting from the root directory) or relative paths (relative to the script’s location). The os module provides functions for manipulating paths and directories.

import os

current_directory = os.getcwd()
print(f"Current directory: {current_directory}")

file_path = os.path.join(current_directory, "my_file.txt")
print(f"File path: {file_path}")

if os.path.exists(file_path):
    print(f"File '{file_path}' exists.")
else:
    print(f"File '{file_path}' does not exist.")

This guide provides a foundational understanding of Python file handling. Further exploration into more advanced techniques, such as CSV and JSON file processing, is encouraged.