How to save the result of this code in a list?

Asked

Viewed 339 times

0

I made the following code in python:

def exibir_menu():

    print('''Escolha uma opção:

    1. Cadastrar um aluno
    2. Listar alunos matriculados
    3. Procurar um aluno
    ''')


def cadastrar(pessoas):

    nome = input('Nome: ')     
    email = input('Email: ')
    curso = (input('Curso: '))
    pessoas.append((nome, email, curso))


def listar(pessoas):

    for pessoa in pessoas:
        nome, email, curso = pessoa
        print(f'Nome: {nome}, email: {email}, curso: {curso}')

def buscar(pessoas):

    pessoa_desejada = input('Nome: ')
    for pessoa in pessoas:
        nome, email, curso = pessoa
        if nome == pessoa_desejada:
            print(f'Nome: {nome}, email: {email}, curso: {curso}')
            break
    else:
        print(f'Pessoa com nome {pessoa_desejada} não encontrada')

def main():
    pessoas = []

    while True:
        exibir_menu()
        opcao = int(input('Opção? '))
        if opcao == 1:
            cadastrar(pessoas)
        elif opcao == 2:
            listar(pessoas)
        elif opcao == 3:
            buscar(pessoas)
        else:
            print('Opção inválida')


main()

Now I would like to save the registration (name, email, course) in a file . txt, as I do?

  • Do you know how to handle files with Python, open for reading or writing, write to the file, etc? Or is that your question?

2 answers

2

You can use the following functions:

def salvar(filename, info):
    file = open('{}.txt'.format(filename),'a', encoding='UTF-8')
    file.write(info+'\n')
    file.close()
    
def ler(filename):
    file = open('{}.txt'.format(filename),'r', encoding='UTF-8')
    return file.read()

In this case, you would only have to pass the desired file name in 'filename' and the information formatted in 'info' to save.

I use the ' n' to add a line, so that each time I save, I save and create a line below for the future record.

In the save() function I use the read with 'a' (append) to add information, instead of overwriting (if it was just 'w' [write]). To know about file reading, can make a quick read this link in W3C

BUT!

I would particularly recommend you save to file. csv, since it can be used easily by Excel/Drive spreadsheets, in database or consumed by other systems.

0

If the use of the data is for use only in Python you can think about using the library pickle which is standard in Python distributions.

import pickle
l = [1,2,3,4]
with open("test.txt", "wb") as fp:
   pickle.dump(l, fp)

with open("test.txt", "rb") as fp:
  b = pickle.load(fp)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.