Python for Beginners: Learn to Code from Zero · Lesson 9 of 10

Lesson 9: Handling Errors and Working with Files

Stop programs from crashing with try/except, and save and read data using files.

Lesson 9: Handling Errors and Working with Files

Errors (exceptions)

When something goes wrong, Python stops and shows an error. Dividing by zero is a classic:

print(10 / 0)
ZeroDivisionError: division by zero

To keep the program running, wrap risky code in try and say what to do in except.

try:
    number = int("abc")
    print(number)
except ValueError:
    print("That was not a number")
print("The program keeps going")

Output:

That was not a number
The program keeps going

A friendly input loop that keeps asking until it gets a valid number (run it on your own computer):

while True:
    try:
        age = int(input("Your age: "))
        break
    except ValueError:
        print("Please type digits only")
print("Thank you")

Writing a file

open(name, "w") opens a file for writing (it replaces anything already there). Using with closes the file for you automatically.

with open("marks.txt", "w") as f:
    f.write("Sita,72\n")
    f.write("Ram,85\n")
print("saved")

Output:

saved

Reading a file

with open("marks.txt", "w") as f:
    f.write("Sita,72\nRam,85\n")

with open("marks.txt") as f:
    for line in f:
        name, marks = line.strip().split(",")
        print(name, int(marks) + 5)

Output:

Sita 77
Ram 90

Use "a" instead of "w" to append to the end of a file without erasing it. If a file might not exist, catch FileNotFoundError.

Try it yourself

  1. Write a program that saves three of your friends' names to a file, one per line.
  2. Read the file back and print each name in capitals.
  3. Wrap your reading code in try/except so a missing file prints a friendly message.

Next lesson: put everything together in a mini project.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 9: Handling Errors and Working with Files | MeroSir