File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ # Basic File Handling
2+
3+
4+ ## Writing
5+
6+ Open file in current directory to overwrite file contents. Creates file if it doesn't exist.
7+ ```
8+ file = open("file.txt", "w")
9+ file.write("hello earth!")
10+ ```
11+ File contents:
12+ ```
13+ hello earth!
14+ ```
15+ ## Reading
16+
17+ Open file for read only. Read entire contents of file.
18+ ```
19+ file = open("file.txt", "r")
20+ file_contents = file.read()
21+ ```
22+ Reads:
23+ ```
24+ hello earth!
25+ ```
26+
27+ ## Appending
28+
29+ Open file for appending. This means the existing file content is kept.
30+ ```
31+ file = open("file.txt", "a")
32+ file.write("\nhello universe!") # note:"\n" writes a newline
33+ ```
34+ File contents:
35+ ```
36+ hello earth!
37+ hello universe!
38+ ```
39+ ## Read file line by line
40+
41+ Make a list holding each line in the file
42+ ```
43+ file = open("file.txt", "r")
44+ lines_in_file = file.readlines()
45+
46+ for each_line in lines_in_file:
47+ print(each_line)
48+ ```
49+ prints:
50+ ```
51+ hello earth!
52+ hello universe!
53+ ```
54+
55+ ## Check if file exists
56+
57+ ```
58+ from pathlib import Path
59+
60+ file_to_find = Path("file.txt")
61+
62+ if file_to_find.exists():
63+ print("file exists")
64+ else:
65+ print("file not found")
66+ ```
67+
68+ ## Delete file
69+
70+ ```
71+ from pathlib import Path
72+
73+ file_to_delete = Path("file.txt")
74+ file_to_delete.unlink()
75+ ```
You can’t perform that action at this time.
0 commit comments