-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path64 - Banco de dados.py
92 lines (76 loc) · 2.44 KB
/
64 - Banco de dados.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
def creating_file(file):
try: # Tentar abrir arquivo de texto
file_name = open(file, 'rt')
except FileNotFoundError: # Criar arquivo de texto caso não exista
file_name = open(file, 'wt+')
except:
print('Houve um erro na criação do arquivo.')
else:
file_name.close()
def header(text='menu principal', upper=True):
global line
line = 40
print('-' * line)
print(text.upper().center(line)) if upper else print(text.capitalize().center(line))
print('-' * line)
def menu():
header('''1 - ver pessoas cadastradas
2 - cadastrar nova pessoa
3 - sair do programa''')
while True:
try:
option = int(input('Sua opção: '))
if option < 1 or option > 3: raise Exception()
except (ValueError, TypeError):
print('ERRO. Digite um número inteiro válido.')
except:
print('ERRO. Digite uma opção válida.')
else:
return option
def show_people(file):
try:
file_txt = open(file, 'rt')
except:
print('Erro ao tentar ler o arquivo.')
else:
header('pessoas cadastradas', False)
for p in file_txt:
person = p.split('-')
person[1] = person[1].replace('\n', '')
print(f'{person[0]:<{line-8}}{person[1]:>3} anos')
file_txt.close()
def register(file):
try:
file_txt = open(file, 'at')
except:
print('Erro ao tentar abrir o arquivo.')
else:
header('cadastro de pessoa', False)
name = str(input('Insira o nome: '))
while True:
try:
age = int(input('Insira a idade: '))
break
except:
print('Insira uma idade válida.')
try:
file_txt.write(f'{name}-{age}\n')
except:
print('Erro ao tentar adicionar registro ao arquivo.')
else:
print(f'Registro de {name} adicionado.')
file_txt.close()
def main():
header()
# Primeiro cria-se o arquivo de texto caso ainda não exista
file_name = input('Qual o nome do arquivo de texto? ') + '.txt'
creating_file(file_name)
# Iniciar programa de fato
while True:
user_option = menu()
if user_option == 1: show_people(file_name)
elif user_option == 2: register(file_name)
else:
header('Finalizando o programa...')
break
main()