Kahibaro
Discord Login Register

10.5 Simple file-based programs

Why Build File-Based Programs?

By now you know how to open, read, and write files. In this chapter, you’ll use those skills to create small, practical programs that:

You’ll see complete mini-programs that are still simple enough for beginners to read and modify.


General Pattern for File-Based Programs

Most simple file-based programs follow this pattern:

  1. Get input
    • From the user (input())
    • From a file (using open() and .read() / .readline() / looping)
  2. Process the data
    • Do calculations, filtering, counting, or formatting
  3. Save or display the result
    • Print to the screen
    • Write to a file with write() or writelines()

You can think of it like a factory:

$$
\text{File(s) + User Input} \;\rightarrow\; \text{Your Code} \;\rightarrow\; \text{Output File(s) + Screen Output}
$$


Example 1: A Simple Note Saver

This program lets the user type a note, and then saves it to a text file. Each note is added on a new line.

# simple_note_saver.py
filename = "notes.txt"
note = input("Type your note: ")
# Add the note to the file, keeping old notes
with open(filename, "a", encoding="utf-8") as file:
    file.write(note + "\n")
print("Note saved to", filename)

Key ideas specific to this style of program:

Try extending it:

Example 2: Viewing Saved Notes

Now add a second program to read and show the notes you saved.

# view_notes.py
filename = "notes.txt"
try:
    with open(filename, "r", encoding="utf-8") as file:
        contents = file.read()
    if contents.strip() == "":
        print("No notes found.")
    else:
        print("Your notes:")
        print(contents)
except FileNotFoundError:
    print("No notes file found yet. Add a note first.")

New pattern here:

Example 3: A Very Simple Log Counter

Imagine you have a file log.txt where every line is some kind of event:

# Example log.txt
login
view_page
logout
login
view_page
view_page
logout

You can write a program that counts how many times each event appears.

# count_events.py
filename = "log.txt"
counts = {}
with open(filename, "r", encoding="utf-8") as file:
    for line in file:
        event = line.strip()
        if event == "":
            continue  # skip empty lines
        if event in counts:
            counts[event] += 1
        else:
            counts[event] = 1
print("Event counts:")
for event, count in counts.items():
    print(event, "=>", count)

What’s specific to this style of program:

You can adapt this pattern to:

Example 4: Copying and Transforming a File

This program reads one file and writes a modified version to a new file. For example, you can convert all text to uppercase.

# shout_copy.py
source = "input.txt"
target = "output_shout.txt"
with open(source, "r", encoding="utf-8") as in_file, \
     open(target, "w", encoding="utf-8") as out_file:
    for line in in_file:
        upper_line = line.upper()
        out_file.write(upper_line)
print("Created", target)

Specific techniques here:

You could change:

Example 5: Simple To-Do List (File-Based)

This example combines input, output, and file storage into one simple program.

It will:

  1. Load tasks from a file (if it exists)
  2. Show a menu to the user
  3. Let the user:
    • Add a task
    • View tasks
    • Save and quit
# todo_list.py
FILENAME = "tasks.txt"
def load_tasks():
    tasks = []
    try:
        with open(FILENAME, "r", encoding="utf-8") as file:
            for line in file:
                task = line.strip()
                if task:
                    tasks.append(task)
    except FileNotFoundError:
        # No file yet, start with empty list
        pass
    return tasks
def save_tasks(tasks):
    with open(FILENAME, "w", encoding="utf-8") as file:
        for task in tasks:
            file.write(task + "\n")
def show_tasks(tasks):
    if not tasks:
        print("No tasks yet.")
    else:
        print("Your tasks:")
        for i, task in enumerate(tasks, start=1):
            print(f"{i}. {task}")
def main():
    tasks = load_tasks()
    while True:
        print("\nMenu:")
        print("1. View tasks")
        print("2. Add task")
        print("3. Save and quit")
        choice = input("Choose an option (1-3): ")
        if choice == "1":
            show_tasks(tasks)
        elif choice == "2":
            new_task = input("Enter a new task: ")
            if new_task.strip():
                tasks.append(new_task.strip())
                print("Task added.")
            else:
                print("Empty task not added.")
        elif choice == "3":
            save_tasks(tasks)
            print("Tasks saved. Goodbye!")
            break
        else:
            print("Invalid choice. Please try again.")
if __name__ == "__main__":
    main()

What’s important about this example:

Ideas to extend:

Example 6: Searching in a File

This program asks the user for a word and then shows all lines from a file that contain that word.

# search_in_file.py
filename = "data.txt"
word = input("Enter a word to search for: ").strip()
if not word:
    print("You did not enter a word.")
else:
    try:
        with open(filename, "r", encoding="utf-8") as file:
            found_any = False
            for line_number, line in enumerate(file, start=1):
                if word in line:
                    print(f"Line {line_number}: {line.rstrip()}")
                    found_any = True
        if not found_any:
            print("No matches found.")
    except FileNotFoundError:
        print("File", filename, "not found.")

This shows a very common file-based pattern:

Combining Ideas: Design Tips for Simple File Programs

When designing your own file-based programs:

  1. Decide what the file represents
    • One item per line (tasks, notes, events)
    • One line with many values
    • Multiple files for different categories
  2. Choose how data is updated
    • Append new data ("a")
    • Rewrite the whole file ("w") after changes
    • Read-result → modify in memory → save once at the end
  3. Handle missing files gracefully
    • Use try / except FileNotFoundError
    • Start from an empty list or empty string if no file exists
  4. Keep the format simple
    • Start with “one thing per line”
    • Use simple separators like | or , only when needed
  5. Separate logic into functions
    • One function to load data from the file
    • One function to save data
    • Other functions to process the data

Practice Ideas

Here are small projects you can try to practice building file-based programs:

In each case, think about:

These simple patterns are the foundation for more advanced programs that work with larger data files, configuration files, or even simple databases.

Views: 80

Comments

Please login to add a comment.

Don't have an account? Register now!