Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ca17084

Browse files
add md showing basic file handling
1 parent 5c66dbf commit ca17084

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

‎snippets/python/basic_file_handling.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /