'How to register and than search a value in CSV file?
I'm trying to register an user and then read the data I just appended. It looks like the csv file is appending the value, but it's not saving it. But this is awkward, because I used the "with open" function at the "registered" function.
def is_registered(ID): #OK
df = read_any_csv(users_path)
x = df.loc[df["ID"] == ID]
if x.empty:
return False
else:
return True
#faz o cadastro do usuario
def register(ID): #OK
x = str(input("Escreva seu nome: "))
name = x.title()
section = int(input("Digite seu setor(111/112/113): "))
data = [name,ID,section]
with open (users_path,'a') as file:
writer = csv.writer(file)
writer.writerow(data)
def start():
#Se o usuario estiver registrado, da as boas vindas a ele, caso nao, registra ele e depois da as boas vindas
if is_registered(ID) == True: #OK
current_user = users_df.loc[users_df["ID"] == ID]
name = current_user["NAME"]
name2 =(name.to_string(index=False))
section = current_user["SECTION"]
print(f"Ola, {name2}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
videos = videos_to_watch(section)
print("Esses sao os videos que faltam serem assistidos:\n")
print(*videos,sep = '\n')
else: #OK
register(ID)
users_df.to_csv("Users.csv",index = False)
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
But the csv can't find the data, the result that I got is that:
Digite o ID: aaaaa
Escreva seu nome: leo
Digite seu setor(111/112/113): 113
Empty DataFrame
Columns: [NAME, ID, SECTION]
Index: []
What I actually want is:
Digite o ID: 5DBEF04B
Escreva seu nome: Raul Lopes Camina
Digite seu setor(111/112/113): 113
Ola, Raul Lopes Camina, bem vindo ao programa de treinamento Mercedes Benz Brasil!
Solution 1:[1]
You write new data to file but this can't change original users_df and you would have to read it again (instead of write again)
register(ID)
users_df = pd.read_csv("Users.csv") # <-- read instead of write
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
Or you should first add to users_df and later save it with to_csv - and then you don't have to read it again.
def register(ID): # OK
global users_df # need it to add to external variable
name = str(input("Escreva seu nome: "))
name = name.title()
section = int(input("Digite seu setor(111/112/113): "))
data = pd.DataFrame({'NAME': [name], 'ID': [ID], 'SECTION': [section]})
users_df = pd.concat([users_df, data]) # <-- add to original `users_df`
users_df.to_csv("Users.csv", index=False)
and later
register(ID)
# without `to_csv()` and `read_csv()`
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | furas |
