-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnames_csv.py
More file actions
77 lines (57 loc) · 1.99 KB
/
names_csv.py
File metadata and controls
77 lines (57 loc) · 1.99 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
import csv
import os
from generals import is_valid_number, text_to_number
CAREERS = [
"Electrical Engineering",
"Mechanical Engineering",
"Civil Engineering",
"Computer Engineering",
"Industrial Engineering"
]
def main():
# Ask how many pupils
while True:
n = input("How many pupils? ")
if not is_valid_number(n):
print("Error: please enter a valid number.")
continue
n = text_to_number(n)
if n <= 0:
print("Error: number must be greater than 0.")
continue
break
file_exists = os.path.exists("pupils.csv")
file_is_empty = not file_exists or os.stat("pupils.csv").st_size == 0
# Write pupils to CSV
with open("pupils.csv", "a", newline="") as file:
writer = csv.writer(file)
# Write headers only once
if file_is_empty:
writer.writerow(["Name", "Engineering"])
for _ in range(n):
name = input("Pupil full name: ").strip()
# Career selection
while True:
print("\nChoose a career:")
for i, career in enumerate(CAREERS, start=1):
print(f"{i}. {career}")
option = input("Option number: ")
if not is_valid_number(option):
print("Error: choose a valid option number.")
continue
option = int(text_to_number(option))
if option < 1 or option > len(CAREERS):
print("Error: option out of range.")
continue
career = CAREERS[option - 1]
break
writer.writerow([name, career])
print("Pupil saved!\n")
# Read pupils from CSV
print("\n📋 Pupils list:")
with open("pupils.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"- {row['Name']} — {row['Engineering']}")
if __name__ == "__main__":
main()