Dateien lesen/schreiben und Fehlerbehandlung
# 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())
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.")
→ kapitel_10_aufgaben_10-1_10-3.ipynb
↓ Lösungen
# 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)
# 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())
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.
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.
# 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())
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.
# 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)
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 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")
→ kapitel_10_aufgaben_10-4_10-5.ipynb
↓ Lösungen
# 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.")
What is your name? Alice
Hello Alice, your name has been recorded.
# 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")
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
# 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.")
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)
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)
→ kapitel_10_aufgaben_10-6_10-10.ipynb
↓ Lösungen
# 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}")
Enter first number: 5
Enter second number: 3
The sum is: 8
# 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
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
# 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.")
Reading cats.txt:
Sorry, cats.txt was not found.
Reading dogs.txt:
Sorry, dogs.txt was not found.
# 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
# No output since files don't exist and errors are silently passed
# 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")
Sorry, alice.txt was not found.
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()
→ kapitel_10_aufgaben_10-11_10-14.ipynb
↓ Lösungen
# 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}.")
What's your favorite number? 7
I know your favorite number! It's 7.
# 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}.")
I know your favorite number! It's 7.
# 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)
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']}!")
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!
# 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()
Are you Alice? (y/n): y
Welcome back, Alice!
# 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)