-
Notifications
You must be signed in to change notification settings - Fork 303
Expand file tree
/
Copy pathfiles.py
More file actions
73 lines (55 loc) · 1.32 KB
/
files.py
File metadata and controls
73 lines (55 loc) · 1.32 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
# r = Read
# a = Append
# w = Write
# x = Create
# Read - error if it doesn't exist
f = open("names.txt")
# print(f.read())
# print(f.read(4))
# print(f.readline())
# print(f.readline())
for line in f:
print(line)
f.close()
try:
f = open("names.txt")
print(f.read())
except:
print("The file you want to read doesn't exist")
finally:
f.close()
# Append - creates the file if it doesn't exist
f = open("names.txt", "a")
f.write("Neil\n")
f.close()
f = open("names.txt")
print(f.read())
f.close()
# Write (overwrite)
f = open("context.txt", "w")
f.write("I deleted all of the context")
f.close()
f = open("context.txt")
print(f.read())
f.close()
# Two ways to create a new file
# Opens a file for writing, creates the file if it does not exist
f = open("name_list.txt", "w")
f.close()
# Creates the specified file, but returns an error if the file exists
if not os.path.exists("dave.txt"):
f = open("dave.txt", "x")
f.close()
# Delete a file
# avoid an error if it doesn't exist
if os.path.exists("dave.txt"):
os.remove("dave.txt")
else:
print("The file you wish to delete does not exist")
# with has built-in implicit exception handling
# close() will be automatically called
with open("more_names.txt") as f:
content = f.read()
with open("names.txt", "w") as f:
f.write(content)