-
Notifications
You must be signed in to change notification settings - Fork 13
/
extra_features_database_project.py
96 lines (84 loc) · 2.77 KB
/
extra_features_database_project.py
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
93
94
95
96
#imports
import csv
#Variables
current_ID = 1
new_additions = []
filename = "library.csv"
fields = ['ID', 'Title', 'Author', 'Genre', 'Year', 'Location']
data = []
#Code
with open(filename, 'w+') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(dict(row))
if len(data) > 0:
current_ID = data[:-1].get("ID")
current_ID = int(current_ID) + 1
print("------Welcome to the Python Library organiser------")
choice = ""
while choice.lower() != "x":
print("""What would you like to do?
1 - Add a book
2 - Display your Books
3 - Search for a Book""")
choice = input(">")
if choice == "1":
#Code to add a record
new_record = {
"ID": current_ID,
"Title": input("What is the title of the book? >"),
"Author": input("What is the author's first name? >"),
"Genre": input("What genre is the book? >"),
"Year": input("What year was the book released? >"),
"Location": input("Where is the book? > ")
}
new_additions.append(new_record)
current_ID = current_ID + 1
print("-"*15)
print("New Record added successfully!")
elif choice == "2":
#Display the data
for item in fields:
print("%-25s"%item, end='')
print("\n")
for row in data:
for key, val in row.items():
print("%-25s"%val, end='')
print("\n")
for row in new_additions:
for key, val in row.items():
print("%-25s"%val, end='')
print("\n")
elif choice == "3":
#Search the data
search_term = input("What would you like to search for?").lower()
results = []
for row in data:
for key, val in row.items():
if search_term in val.lower():
results.append(row)
for item in new_additions:
for key, val in item.items():
if search_term in val.lower():
results.append(item)
#Display the results
if len(results) > 0:
for item in fields:
print("%-25s"%item, end='')
print("\n")
for item in results:
for key, val in item.items():
print("%-25s"%val, end='')
print("\n")
else:
print("Sorry no records found")
elif choice.lower() == "x":
print("Thank you! Shutting down.")
else:
print("Sorry, I didnt recognise that option")
if len(new_additions) > 0:
with open(filename, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fields)
writer.writeheader()
for item in new_additions:
writer.writerow(item)