python-kurs-softed/beispiele/readfile6.py

39 lines
1.1 KiB
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
try:
name, raw_data = line.split(":", 1) # split line at first colon
except ValueError as exc:
print(f"Warning: could not parse line {i+1}: {exc}")
else:
try:
# split raw data at commas
items = [int(item.strip()) for item in raw_data.split(",")]
except (ValueError, TypeError) as exc:
print(f"Warning: could not parse data on line {i+1}: {exc}")
else:
data[name.strip()] = items
except OSError as exc:
print(f"Could not open file {filename}: {exc}")
for key in data:
print(key, data[key])