Python Files & Exceptions

Working with files and handling exceptions in Python including reading, writing, and error handling.

Reading Files

# Reading entire file
from pathlib import Path

path = Path('pi_digits.txt')
contents = path.read_text()
print(contents)

# Reading line by line
lines = contents.splitlines()
for line in lines:
    print(line)

Writing Files

# Writing a string to a file
from pathlib import Path

path = Path('programming.txt')
msg = 'I love programming!'
path.write_text(msg)  # overwrites existing file

# Writing multiple lines
contents = 'I love programming.\n'
contents += 'I love creating new games.\n'
path.write_text(contents)

Exceptions

# Handling ZeroDivisionError
try:
    print(5/0)
except ZeroDivisionError:
    print("You cannot divide by zero!")

# Handling FileNotFoundError
path = Path('alice.txt')
try:
    contents = path.read_text()
except FileNotFoundError:
    print(f"The file {path} does not exist.")

The else Block

# Using else with try-except
try:
    answer = 10 / 2
except ZeroDivisionError:
    print("You cannot divide by zero!")
else:
    print(answer)  # runs if no exception