File I/O: Reading and Writing Files in Python #

Welcome back to our programming tutorial series! Today, we’ll explore file I/O (Input/Output), a crucial concept for interacting with files in Python. You’ll learn how to read from and write to files, enabling your programs to store and retrieve data.


Why Use File I/O? #

File I/O allows your program to persist data beyond its runtime. Instead of storing everything in memory, you can save data in a file and access it later, making your programs more versatile and useful.


Opening and Closing Files #

To work with a file in Python, you first need to open it using the built-in open() function. Once you’re done with the file, you should close it to free up system resources.

Example: #

file = open("example.txt", "r")  # Open the file in read mode
data = file.read()  # Read the contents of the file
print(data)
file.close()  # Always close the file after use

File Modes: #

  • 'r': Read (default mode).
  • 'w': Write (overwrites the file).
  • 'a': Append (adds content to the end of the file).
  • 'b': Binary mode (for non-text files like images).

Reading Files #

Python provides several ways to read the contents of a file:

Reading the Entire File: #

file = open("example.txt", "r")
data = file.read()  # Reads the entire file as a single string
print(data)
file.close()

Reading Line by Line: #

file = open("example.txt", "r")
for line in file:
    print(line.strip())  # Strip removes trailing newline characters
file.close()

Reading a File into a List: #

file = open("example.txt", "r")
lines = file.readlines()  # Returns a list where each element is a line in the file
print(lines)
file.close()

Writing to Files #

You can write data to a file using the write() method. If the file doesn’t exist, Python will create it. If it does exist, you can choose to overwrite it or append to it.

Overwriting a File: #

file = open("example.txt", "w")  # Open in write mode (overwrites the file)
file.write("Hello, World!")
file.close()

Appending to a File: #

file = open("example.txt", "a")  # Open in append mode
file.write("\nThis is an additional line.")
file.close()

Using the with Statement: Automatic File Closing #

A better practice for handling files is using the with statement, which automatically closes the file after it’s no longer needed. This reduces the risk of leaving files open accidentally.

Example: #

with open("example.txt", "r") as file:
    data = file.read()
    print(data)  # File is automatically closed when the block finishes

Handling File Exceptions #

When working with files, it’s important to handle exceptions, especially if the file might not exist. You can use try-except blocks to catch potential errors.

Example: #

try:
    with open("nonexistent.txt", "r") as file:
        data = file.read()
except FileNotFoundError:
    print("The file does not exist.")

Working with Binary Files #

In addition to text files, Python allows you to work with binary files, which are often used for images, videos, and other non-text data. To work with binary files, open the file in binary mode ('rb' or 'wb').

Example of Reading a Binary File: #

with open("image.png", "rb") as file:
    data = file.read()
    print(f"Binary data length: {len(data)}")

Example of Writing a Binary File: #

with open("copy_image.png", "wb") as file:
    file.write(data)

Practical Exercise: Build a Simple Log System #

Now that you understand file I/O, try this practical exercise:

  1. Write a program that logs user actions to a file.
  2. Allow the user to enter commands (e.g., “start”, “stop”).
  3. Write each command to a file with a timestamp.
  4. Provide an option to view the log.

Here’s a starter example:

import time

def log_action(action):
    with open("log.txt", "a") as log_file:
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        log_file.write(f"{timestamp}: {action}\n")

while True:
    action = input("Enter action (start/stop/view/quit): ").lower()
    if action == "quit":
        break
    elif action == "view":
        with open("log.txt", "r") as log_file:
            print(log_file.read())
    else:
        log_action(action)

What’s Next? #

You’ve just learned the basics of file I/O, a crucial part of building programs that interact with external data. In the next post, we’ll explore working with APIs, allowing your programs to fetch data from external sources.



Happy coding, and we’ll see you in the next lesson!