From 16ab66c6a8ddc0f434187e468158e4634693739f Mon Sep 17 00:00:00 2001 From: Christopher Arndt Date: Mon, 6 May 2024 07:44:35 +0200 Subject: [PATCH] Add examples for reading files Signed-off-by: Christopher Arndt --- beispiele/readfile1.py | 12 ++++++++++++ beispiele/readfile2.py | 14 ++++++++++++++ beispiele/readfile3.py | 16 ++++++++++++++++ beispiele/readfile4.py | 24 ++++++++++++++++++++++++ 4 files changed, 66 insertions(+) create mode 100644 beispiele/readfile1.py create mode 100644 beispiele/readfile2.py create mode 100644 beispiele/readfile3.py create mode 100644 beispiele/readfile4.py diff --git a/beispiele/readfile1.py b/beispiele/readfile1.py new file mode 100644 index 0000000..1c3a716 --- /dev/null +++ b/beispiele/readfile1.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +import sys + +filename = sys.argv[1] + +with open(filename, "rb") as fileobj: + data = fileobj.read() + +num_bytes = len(data) + +print(f"The file contents are {num_bytes} long.") diff --git a/beispiele/readfile2.py b/beispiele/readfile2.py new file mode 100644 index 0000000..4995666 --- /dev/null +++ b/beispiele/readfile2.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +import sys + +filename = sys.argv[1] + +with open(filename, "r") as fileobj: + data = fileobj.read() + + max_linelength = 0 + for line in data.splitlines(): + max_linelength = max(max_linelength, len(line)) + +print(f"The longest line has a length of {max_linelength}.") diff --git a/beispiele/readfile3.py b/beispiele/readfile3.py new file mode 100644 index 0000000..12d0b20 --- /dev/null +++ b/beispiele/readfile3.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +import sys + +filename = sys.argv[1] + +with open(filename, "r") as fileobj: + max_linelength = 0 + longest_line = -1 + + for i, line in enumerate(data): + if len(line) > max_linelength: + max_linelength = len(line) + longest_line = i + 1 + +print(f"The longest line is line {longest_line} with a length of {max_linelength}.") diff --git a/beispiele/readfile4.py b/beispiele/readfile4.py new file mode 100644 index 0000000..c942e33 --- /dev/null +++ b/beispiele/readfile4.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +import sys + +filename = sys.argv[1] + +data = {} + +with open(filename, "r") as fileobj: + for i, line in enumerate(data): + 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 + + +for key in data: + print(key, data[key])