Python Crash Course

Kapitel 10

Dateien und Ausnahmen

Dateien lesen/schreiben und Fehlerbehandlung

Dateien lesen

  • Daten persistent speichern und laden
  • with-Statement für sicheren Dateizugriff
  • Automatisches Schließen der Dateien
# Datei lesen
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

# Zeile für Zeile lesen
filename = 'pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

# Als Liste speichern
with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())

Mit Dateiinhalten arbeiten

filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.rstrip()

print(pi_string)
print(len(pi_string))

# Pi-Wert als Zahl
pi_string = ''
for line in lines:
    pi_string += line.strip()

birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi!")
else:
    print("Your birthday does not appear in the first million digits of pi.")

🛠️ Übung 1: Dateien lesen

🔗 jupyter.gymnasium-hummelsbuettel.de

Aufgaben 10-1 bis 10-3:

  • 10-1: Python-Aussagen lesen
  • 10-2: Text ersetzen (Python → C)
  • 10-3: Code vereinfachen

→ kapitel_10_aufgaben_10-1_10-3.ipynb

↓ Lösungen

💡 Lösung 10-1 (Teil 1)

# 10-1: Python-Aussagen - Datei erstellen
content = """In Python you can store data in lists.
In Python you can use loops to repeat actions.
In Python you can define functions to organize code.
In Python you can create classes for complex programs.
In Python you can work with files and data."""

with open('learning_python.txt', 'w') as file:
    file.write(content)

# 1. Ganze Datei lesen
with open('learning_python.txt') as file:
    contents = file.read()
    print("Reading entire file:")
    print(contents)

💡 Lösung 10-1 (Teil 2)

# 2. Schleife über Dateiobjekt
print("\nLooping over file object:")
with open('learning_python.txt') as file:
    for line in file:
        print(line.rstrip())

# 3. Zeilen in Liste speichern
print("\nStoring in a list:")
with open('learning_python.txt') as file:
    lines = file.readlines()
for line in lines:
    print(line.rstrip())

📄 Ausgabe 10-1 (Teil 1)

Reading entire file:
In Python you can store data in lists.
In Python you can use loops to repeat actions.
In Python you can define functions to organize code.
In Python you can create classes for complex programs.
In Python you can work with files and data.

Looping over file object:
In Python you can store data in lists.
In Python you can use loops to repeat actions.
In Python you can define functions to organize code.

📄 Ausgabe 10-1 (Teil 2)

In Python you can create classes for complex programs.
In Python you can work with files and data.

Storing in a list:
In Python you can store data in lists.
In Python you can use loops to repeat actions.
In Python you can define functions to organize code.
In Python you can create classes for complex programs.
In Python you can work with files and data.

💡 Lösung 10-2

# 10-2: Python durch C ersetzen
with open('learning_python.txt') as file:
    lines = file.readlines()

print("Replacing Python with C:")
for line in lines:
    modified_line = line.replace('Python', 'C')
    print(modified_line.rstrip())

📄 Ausgabe 10-2

Replacing Python with C:
In C you can store data in lists.
In C you can use loops to repeat actions.
In C you can define functions to organize code.
In C you can create classes for complex programs.
In C you can work with files and data.

💡 Lösung 10-3

# 10-3: Einfacherer Code
# Vorher:
with open('learning_python.txt') as file:
    lines = file.readlines()
for line in lines:
    print(line.rstrip())

# Nachher - ohne temporäre Variable:
with open('learning_python.txt') as file:
    for line in file.read().splitlines():
        print(line)

📄 Ausgabe 10-3

In Python you can store data in lists.
In Python you can use loops to repeat actions.
In Python you can define functions to organize code.
In Python you can create classes for complex programs.
In Python you can work with files and data.
In Python you can store data in lists.
In Python you can use loops to repeat actions.
In Python you can define functions to organize code.
In Python you can create classes for complex programs.
In Python you can work with files and data.

In Dateien schreiben

# In Datei schreiben (überschreibt Inhalt)
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.")

# Mehrere Zeilen schreiben
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

# An Datei anhängen
filename = 'programming.txt'
with open(filename, 'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

🛠️ Übung 2: Dateien schreiben

Aufgaben 10-4 und 10-5:

  • 10-4: Gastbenutzer - Namen in Datei
  • 10-5: Gästebuch - while-Schleife

→ kapitel_10_aufgaben_10-4_10-5.ipynb

↓ Lösungen

💡 Lösung 10-4

# 10-4: Gastbenutzer
name = input("What is your name? ")
with open('guest.txt', 'w') as file:
    file.write(name)

print(f"Hello {name}, your name has been recorded.")

📄 Ausgabe 10-4

What is your name? Alice
Hello Alice, your name has been recorded.

💡 Lösung 10-5

# 10-5: Gästebuch
filename = 'guest_book.txt'

while True:
    name = input("\nWhat is your name? (Enter 'quit' to exit): ")
    if name == 'quit':
        break
    
    print(f"Hello {name}, thanks for visiting!")
    
    with open(filename, 'a') as file:
        file.write(f"{name} visited our site.\n")

📄 Ausgabe 10-5

What is your name? (Enter 'quit' to exit): Bob
Hello Bob, thanks for visiting!

What is your name? (Enter 'quit' to exit): Charlie
Hello Charlie, thanks for visiting!

What is your name? (Enter 'quit' to exit): quit

Ausnahmen behandeln

# ZeroDivisionError behandeln
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

# FileNotFoundError behandeln
filename = 'alice.txt'
try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exist.")
else:
    # Datei wurde erfolgreich gelesen
    words = contents.split()
    num_words = len(words)
    print(f"The file {filename} has about {num_words} words.")

Mit mehreren Dateien arbeiten

def count_words(filename):
    """Count the approximate number of words in a file."""
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exist.")
    else:
        words = contents.split()
        num_words = len(words)
        print(f"The file {filename} has about {num_words} words.")

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt']
for filename in filenames:
    count_words(filename)

Fehler stillschweigend übergehen

def count_words_silent(filename):
    """Count words - ignore missing files silently."""
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        pass  # Fehler ignorieren
    else:
        words = contents.split()
        num_words = len(words)
        print(f"The file {filename} has about {num_words} words.")

# Verwendung - zeigt nur gefundene Dateien an
for filename in filenames:
    count_words_silent(filename)

🛠️ Übung 3: Ausnahmen

Aufgaben 10-6 bis 10-10:

  • 10-6/7: Addition mit ValueError
  • 10-8/9: Katzen und Hunde
  • 10-10: Häufige Wörter zählen

→ kapitel_10_aufgaben_10-6_10-10.ipynb

↓ Lösungen

💡 Lösung 10-6

# 10-6: Addition
try:
    first_number = int(input("Enter first number: "))
    second_number = int(input("Enter second number: "))
except ValueError:
    print("Please enter numbers only.")
else:
    sum = first_number + second_number
    print(f"The sum is: {sum}")

📄 Ausgabe 10-6

Enter first number: 5
Enter second number: 3
The sum is: 8

💡 Lösung 10-7

# 10-7: Folge von Additionen
while True:
    try:
        first_number = int(input("\nEnter first number (or 'q' to quit): "))
        second_number = int(input("Enter second number: "))
    except ValueError:
        print("Please enter numbers only.")
    else:
        sum = first_number + second_number
        print(f"The sum is: {sum}")
        
        if input("Continue? (y/n): ").lower() == 'n':
            break

📄 Ausgabe 10-7

Enter first number (or 'q' to quit): 10
Enter second number: 7
The sum is: 17
Continue? (y/n): y

Enter first number (or 'q' to quit): abc
Please enter numbers only.

Enter first number (or 'q' to quit): 2
Enter second number: 4
The sum is: 6
Continue? (y/n): n

💡 Lösung 10-8

# 10-8: Katzen und Hunde
filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:
    print(f"\nReading {filename}:")
    try:
        with open(filename) as f:
            contents = f.read()
            print(contents)
    except FileNotFoundError:
        print(f"Sorry, {filename} was not found.")

📄 Ausgabe 10-8

Reading cats.txt:
Sorry, cats.txt was not found.

Reading dogs.txt:
Sorry, dogs.txt was not found.

💡 Lösung 10-9

# 10-9: Katzen und Hunde ohne Fehlermeldung
filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:
    try:
        with open(filename) as f:
            contents = f.read()
            print(f"\n{filename}:")
            print(contents)
    except FileNotFoundError:
        pass  # Fehler stillschweigend übergehen

📄 Ausgabe 10-9

# No output since files don't exist and errors are silently passed

💡 Lösung 10-10

# 10-10: Häufige Wörter
filename = 'alice.txt'
try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, {filename} was not found.")
else:
    word_count = contents.lower().count('the')
    print(f"'the' appears {word_count} times in {filename}")
    
    word_count_with_space = contents.lower().count('the ')
    print(f"'the ' appears {word_count_with_space} times")

📄 Ausgabe 10-10

Sorry, alice.txt was not found.

Daten speichern mit JSON

import json

# Daten speichern
numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as f:
    json.dump(numbers, f)

# Daten laden
filename = 'numbers.json'
with open(filename) as f:
    numbers = json.load(f)

print(numbers)

# Benutzername speichern und laden
def get_stored_username():
    """Get stored username if available."""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def greet_user():
    """Greet the user by name."""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username}!")
    else:
        username = input("What is your name? ")
        filename = 'username.json'
        with open(filename, 'w') as f:
            json.dump(username, f)
        print(f"We'll remember you when you come back, {username}!")

greet_user()

🛠️ Übung 4: JSON

Aufgaben 10-11 bis 10-14:

  • 10-11: Lieblingszahl speichern
  • 10-12: Lieblingszahl kombiniert
  • 10-13: Benutzerverzeichnis
  • 10-14: Benutzer verifizieren

→ kapitel_10_aufgaben_10-11_10-14.ipynb

↓ Lösungen

💡 Lösung 10-11

# 10-11: Lieblingszahl
import json

# Speichern
favorite_number = input("What's your favorite number? ")
filename = 'favorite_number.json'
with open(filename, 'w') as f:
    json.dump(favorite_number, f)

# Laden
with open(filename) as f:
    favorite_number = json.load(f)
print(f"I know your favorite number! It's {favorite_number}.")

📄 Ausgabe 10-11

What's your favorite number? 7
I know your favorite number! It's 7.

💡 Lösung 10-12

# 10-12: Kombiniert
import json

filename = 'favorite_number.json'
try:
    with open(filename) as f:
        favorite_number = json.load(f)
except FileNotFoundError:
    favorite_number = input("What's your favorite number? ")
    with open(filename, 'w') as f:
        json.dump(favorite_number, f)
    print("Thanks! I'll remember that.")
else:
    print(f"I know your favorite number! It's {favorite_number}.")

📄 Ausgabe 10-12

I know your favorite number! It's 7.

💡 Lösung 10-13 (Teil 1)

# 10-13: Benutzerverzeichnis - Funktionen
import json

def get_user_info():
    """Get user information."""
    username = input("What is your name? ")
    age = input("How old are you? ")
    city = input("What city do you live in? ")
    
    user_dict = {
        'username': username,
        'age': age,
        'city': city
    }
    return user_dict

def save_user_info(user_dict):
    """Save user information to file."""
    filename = 'user_info.json'
    with open(filename, 'w') as f:
        json.dump(user_dict, f)

💡 Lösung 10-13 (Teil 2)

def load_user_info():
    """Load user information from file."""
    filename = 'user_info.json'
    try:
        with open(filename) as f:
            user_dict = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return user_dict

# Hauptprogramm
user_info = load_user_info()
if user_info:
    print(f"Welcome back, {user_info['username']}!")
    print(f"You are {user_info['age']} years old and live in {user_info['city']}.")
else:
    user_info = get_user_info()
    save_user_info(user_info)
    print(f"We'll remember you when you come back, {user_info['username']}!")

📄 Ausgabe 10-13

What is your name? Alice
How old are you? 25
What city do you live in? Hamburg
We'll remember you when you come back, Alice!

💡 Lösung 10-14

# 10-14: Benutzer verifizieren
import json

def get_stored_username():
    """Get stored username if available."""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username."""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username

def greet_user():
    """Greet the user by name."""
    username = get_stored_username()
    if username:
        correct = input(f"Are you {username}? (y/n): ")
        if correct.lower() == 'y':
            print(f"Welcome back, {username}!")
        else:
            username = get_new_username()
            print(f"We'll remember you when you come back, {username}!")
    else:
        username = get_new_username()
        print(f"We'll remember you when you come back, {username}!")

greet_user()

📄 Ausgabe 10-14

Are you Alice? (y/n): y
Welcome back, Alice!

Zusammenfassung Kapitel 10

  • Dateien lesen: open(), with-Statement
  • Dateien schreiben: Modi 'w' und 'a'
  • Ausnahmen: try-except-else-finally
  • FileNotFoundError: Fehlende Dateien
  • JSON: Daten strukturiert speichern
  • Robuste Programme: Fehlerbehandlung

Praktische Tipps

  • with-Statement: Immer für Dateizugriff verwenden
  • Encoding: UTF-8 für Textdateien angeben
  • Ausnahmen: Spezifische Exceptions abfangen
  • JSON: Für strukturierte Daten verwenden
# Gute Praxis
try:
    with open('data.txt', encoding='utf-8') as f:
        content = f.read()
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("Permission denied")

# JSON für komplexe Daten
data = {'name': 'Alice', 'scores': [85, 92, 78]}
with open('data.json', 'w') as f:
    json.dump(data, f)