IntermediateLesson 7 of 12
Strings & Files – Python
Processing text, reading and writing files.
Strings have many useful methods. They are immutable – every method returns a new string.
s = " Python is fun "
print(s.strip().lower()) # python is fun
print("a,b,c".split(",")) # ['a', 'b', 'c']
print("-".join(["x", "y", "z"])) # x-y-z
print("Python".replace("y", "Y"), "abc".startswith("a"))
print("Python"[::-1]) # nohtyPThe best way to open files is with with – then they are closed automatically.
with open("notizen.txt", "w", encoding="utf-8") as f:
f.write("Line 1\nLine 2\n")
with open("notizen.txt", encoding="utf-8") as f:
for zeile in f:
print(zeile.strip())TipFor paths, use
pathlib.Path – e.g. Path("daten") / "datei.txt" works on any operating system.