python-kurs-softed/beispiele/readfile5.py

30 lines
709 B
Python
Raw Normal View History

#!/usr/bin/env python
import sys
if len(sys.argv) >= 2:
filename = sys.argv[1]
else:
filename = "data.txt"
data = {}
try:
with open(filename, "r") as fileobj:
for i, line in enumerate(fileobj):
line = line.strip() # remove whitespace from start/end of line
if line.startswith('#'):
# ignore comment lines
continue
name, raw_data = line.split(":", 1) # split line at first colon
items = raw_data.split(",") # split raw data at commas
data[name.strip()] = items
except OSError as exc:
print(f"Could not open file {filename}: {exc}")
for key in data:
print(key, data[key])