Working with Files in Python – Reading and Writing Data

File handling allows your Python programs to read data from files and save data to files, making your applications more practical and useful.

Reading Files

Use the open() function to read files:

# 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

Writing Files

Create or overwrite files with write mode:

# Write to a file
with open("output.txt", "w") as file:
    file.write("Hello, File!\\n")
    file.write("This is line 2\\n")

# Write multiple lines
lines = ["Line 1\\n", "Line 2\\n", "Line 3\\n"]
with open("output.txt", "w") as file:
    file.writelines(lines)

Appending to Files

Add content to existing files without overwriting:

with open("log.txt", "a") as file:
    file.write("New log entry\\n")

File Modes

Different modes for different operations:

"r"  # Read mode (default)
"w"  # Write mode (overwrites existing content)
"a"  # Append mode (adds to end of file)
"r+" # Read and write mode

Handling File Errors

Use try-except to handle file errors gracefully:

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")
except PermissionError:
    print("Permission denied!")

Practical Example: Simple Data Logger

import datetime

def log_message(message):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("activity.log", "a") as file:
        file.write(f"[{timestamp}] {message}\\n")

# Usage
log_message("Program started")
log_message("User logged in")
log_message("File processed successfully")

The with statement ensures files are properly closed even if errors occur, making your file operations safer and more reliable.

Author

  • Mohammad Golam Dostogir, Software Engineer specializing in Python, Django, and AI solutions. Active contributor to open-source projects and tech communities, with experience delivering applications for global companies.
    GitHub

    View all posts
Index