File Handling in Python: Reading and Writing Files the Easy Way

Learning Python for Beginners — Part 6

By Data Impala

Welcome back to our Python learning series at Data Impala! In the last lesson, we explored how to create functions and write tidy, organized Python code

Today, we’re diving into another essential skill every Python learner needs: how to work with files.

Working with files is something you’ll often do for analyzing data, saving logs, or reading configuration details.

This article will take you through the basics of reading, writing, and updating text files using Python.

Let’s walk through everything step by step.

Why File Handling Matters

When you’re working with real-world projects, you can’t always rely on copy-pasting data into your code. 

You’ll often need to load it from a file or save outputs to a file for later use. 

Python makes it simple to do both.

Opening a File in Python

The open() function is the main way to interact with files in Python.

Syntax:

open(file_name, mode)
  • file_name: Name or path of the file
  • mode: What you want to do with the file

Common Modes:

ModeMeaning
‘r’Read only (default)
‘w’Write (overwrites)
‘a’Appends to file
‘x’Create new file
‘b’Binary mode

Example:

file = open("hello.txt", "r")

This opens hello.txt in read mode.

But there’s a better way to open files safely…

with open("hello.txt", "r") as file:
    content = file.read()
    print(content)

This is better than just open() alone because:

  • It automatically closes the file after you’re done
  • It prevents accidental file corruption or memory issues

Reading from a File

1. read()

Reads the whole file as one long string.

with open("data.txt", "r") as file:
    print(file.read())

2. readline()

Reads just one line.

with open("data.txt", "r") as file:
    line = file.readline()
    print(line)

3. readlines()

Reads all lines as a list.

with open("data.txt", "r") as file:
    lines = file.readlines()
    print(lines)

Writing to a File

Use write mode (‘w’) to start fresh. It erases anything already in the file.

Example:

with open("notes.txt", "w") as file:
    file.write("Python is fun!\n")
    file.write("File handling is easy.")

If notes.txt didn’t exist, Python will create it. If it did exist, it will be overwritten.

Appending to a File

Use append mode (‘a’) to add new lines without deleting old ones.

with open("notes.txt", "a") as file:
    file.write("\nLet's add more text.")

Writing Lists to a File

If you have a list and want to save it to a file:

lines = ["Line one\n", "Line two\n", "Line three\n"]
with open("mylist.txt", "w") as file:
    file.writelines(lines)

Note: It doesn’t add line breaks automatically, so each string should end with \n.

Reading and Writing Files Together

Sometimes you need to read content, change it, and save the new version.

with open("file.txt", "r") as file:
    data = file.read()

updated_data = data.replace("old", "new")

with open("file.txt", "w") as file:
    file.write(updated_data)

File Does Not Exist?

If you try to open a file that doesn’t exist using ‘r’, you’ll get an error. But if you use ‘w’ or ‘a’, Python will create the file.

Catching File Errors

Use try-except blocks to catch problems, like missing files:

try:
    with open("nofile.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("Oops! The file doesn’t exist.")

Extra Tip: Working with CSV Files

CSV files are just text files with comma-separated values. You can read them like any other file:

with open("data.csv", "r") as file:
    for line in file:
        print(line.strip().split(","))

This breaks each line into a list by splitting on commas.

For larger CSV projects, Python’s csv module is handy.

Review Summary

Use open() with a file name and mode to start.

Prefer with open(…) as to avoid file-close issues.

Use read(), readline(), or readlines() to read.

Use write() or writelines() to write.

Append mode adds to existing content.

Always handle errors like missing files.

Practice Test: File Editor Mini Project

Goal: Create a simple script that:

  1. Asks the user for a filename.
  2. Lets them choose to read, write, or append.
  3. Performs the action.

Example Code Challenge

# Ask the user to enter the name of the file
filename = input("Enter the file name: ")

# Ask what action they want to take: read, write, or append
mode = input("Choose mode - read / write / append: ")

# If user selects 'read', try to read the file content
if mode == "read":
    try:
        with open(filename, "r") as file:
            print(file.read())  # Display the file content
    except FileNotFoundError:
        print("File not found.")  # Show error if file is missing

# If user selects 'write', ask for new text and overwrite the file
elif mode == "write":
    text = input("Enter text to write: ")
    with open(filename, "w") as file:
        file.write(text)
    print("File written.")

# If user selects 'append', add new text to the existing content
elif mode == "append":
    text = input("Enter text to append: ")
    with open(filename, "a") as file:
        file.write("\n" + text)  # Add a new line before appending
    print("Text added.")

# If none of the above, the mode is invalid
else:
    print("Invalid mode selected.")

✅ Solution Breakdown

  • input() collects user choices
  • Depending on mode, it opens the file in the right way
  • try-except catches missing file problems when reading
  • Uses write() or append() based on choice

This gives you a feel of a basic file tool!

Up Next

We’ll explore handling errors and exceptions in Python — how to keep your code from crashing unexpectedly in the next part. Stay curious and keep experimenting!

Visit more lessons, datasets, and practice sheets at Data Impala — your companion in learning practical Python.

✍️ Written by Ahnaf Chowdhury

📘 Series: Learning Python for Beginners — Part 6

Leave a Comment

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

Scroll to Top