forked from dbwebb-se/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_file.py
More file actions
92 lines (71 loc) · 1.74 KB
/
string_file.py
File metadata and controls
92 lines (71 loc) · 1.74 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env python3
"""
Example of how to read and modify the content of a file
"""
# the name of the file
filename = "items.txt"
def menu():
"""
Print available choices and return input
"""
print(
"""
1. Show file content
2. Add item, append
3. Replace content
4. Remove an item
"""
)
return int(input("Choice: "))
def choice(inp):
"""
Check which action was chosen
"""
if inp == 1:
print(readfile())
elif inp == 2:
write_to_file("\n" + input("Item to add: "), "a")
elif inp == 3:
replace_content()
elif inp == 4:
remove_item()
else:
exit()
def readfile():
"""
Read string from file
"""
with open(filename) as filehandle:
content = filehandle.read()
return content
def write_to_file(content, mode):
"""
Write string to file
"""
with open(filename, mode) as filehandle:
filehandle.write(content)
def replace_content():
"""
Replace content of a file with new items
"""
item = ""
result = ""
while item != "q":
result += item + "\n"
item = input("Item to add: ")
write_to_file(result.strip(), "w")
def remove_item():
"""
Remove an item from the file
"""
content = readfile()
remove = input("What item should be removed: ")
if remove in content: # check if item to remove exists
if content.index(remove) == 0: # if the item is the first line in the file
modified_content = content.replace(remove, "")
else:
modified_content = content.replace("\n" + remove, "")
write_to_file(modified_content.strip(), "w")
if __name__ == "__main__":
while(True):
choice(menu())