Doubts files and lists python

0

I'm starting to program in python, and I've been asked to make a menu that asks the user for the code, name, surname, city and add this to a file.

I've been thinking and it comes to mind, create a list where to enter the data entered by the user and then pass that list to a file ... I've tried several ways but I can not get the program to work. ..if someone can solve a couple of doubts would be very helpful, thanks!

    
asked by kisloty 28.02.2018 в 18:33
source

1 answer

0

then I leave you the simplest way to make the menu using input in case the data record is for a single user:

lista = []

lista.append(input("Introduce tu código: "))
lista.append(input("Introduce tu nombre: "))
lista.append(input("Introduce tu apellido: "))
lista.append(input("Introduce tu ciudad: "))

file = open("datos.txt", "w") 
file.write("Codigo: " + lista[0] + "\n") 
file.write("Nombre: " + lista[1] + "\n") 
file.write("Apellido: " + lista[2] + "\n") 
file.write("Ciudad: " + lista[3] + "\n") 

file.close()

In case you want to save several user registers and using lists as you have indicated (it would be more correct and simple with dictionaries) it would be such that:

lista = []
menu = True
i = 1

while(menu == True):
    lista.append(input("Introduce tu código: "))
    lista.append(input("Introduce tu nombre: "))
    lista.append(input("Introduce tu apellido: "))
    lista.append(input("Introduce tu ciudad: "))
    opt = input("¿Desea continuar? (s/n): ")
    if(opt == "n"):
        menu = False

file = open("datos.txt", "w") 
while(i*4<=len(lista)):
    file.write("Codigo: " + lista[1*i-1] + "\n") 
    file.write("Nombre: " + lista[1*i] + "\n") 
    file.write("Apellido: " + lista[2*i] + "\n") 
    file.write("Ciudad: " + lista[3*i] + "\n\n")
    i += 1

file.close()

This script would update the file only the first time and would overwrite its contents in case of adding records every time you run the script you would have to open the file using file = open("datos.txt", "a") using the "Appending mode" to add new lines of text .

I hope to be of help, greetings.

    
answered by 01.03.2018 / 09:28
source