-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdateien.py
More file actions
executable file
·43 lines (28 loc) · 885 Bytes
/
dateien.py
File metadata and controls
executable file
·43 lines (28 loc) · 885 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3
# Level 4: Dateien
# Pathlib (https://docs.python.org/3/library/pathlib.html) ist die beste Möglichkeit,
# mit Pfaden und Dateien zu hantieren.
from pathlib import Path
# Existiert eine Datei?
Path("lorem_ipsum.txt").exists() # type: bool
# OUT: False
Path("loremipsum.txt").exists()
# OUT: True
# einen Ordner erstellen
test_dir = Path("test")
test_dir.mkdir()
# eine Datei auslesen
# schneller: print(Path("loremipsum.txt").read_text())
lorem_ipsum = Path("loremipsum.txt").open("r")
print(lorem_ipsum.read())
lorem_ipsum.close()
# eine Datei schreiben
# schneller: (test_dir / Path("test.txt")).write_text("total toller Text")
test = (test_dir / Path("test.txt")).open("w")
test.write("total toller Text") # type: int
# OUT: 17
test.close()
# eine Datei löschen
(test_dir / Path("test.txt")).unlink()
# einen Ordner löschen
test_dir.rmdir()