Öffnen, lesen, schreiben
with open(filename, "r+") as file:
if "search pattern" in file.read():
return file
with open(filename, "a") as file:
file.write("Append this.")
with open(filename, "w") as file:
file.writelines("This is written to the file.")
Access Modes
- Read Only (
r
)- Read and Write (
r+
) → Raises I/O error if the file does not exist.- Write Only (
w
)- Write and Read (
w+
) → For an existing file, data is truncated and over-written.- Append Only (
a
)- Append and Read (
a+
)
+
means that the file is created if it doesn’t exist when used for writing and appending.
Working with pathlib
import Path from pathlib
# Two parent directories up from this one
two_dirs_up = Path(__file__).resolve().parent.parent
path = Path.home() / "folder"
# This actually results in "$HOME/folder". I mean... wha-?
Working with os
import os
os.path.join(path, name)
os.listdir(path) # Top level dir
os.walk(path) # Dir and all subdirs
os.path.isfile(file)
os.path.isdir(directory)
Tips and tricks
is_markdown = filename.endswith(".md")
Ressourcen
- Python: Open a file, search then append, if not exist - Stack Overflow
- if statement - Why does python use ‘else’ after for and while loops? - Stack Overflow
- Python: Open a file, search then append, if not exist - Stack Overflow
- How to replace all instances of a string in text file with Python 3? - Stack Overflow