如何注册然后在CSV文件中搜索值?



我正在尝试注册一个用户,然后读取我刚刚附加的数据。看起来csv文件附加了值,但没有保存。但这很尴尬,因为我用了&quot和"函数中的"已注册";函数。

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) 

但是csv找不到数据,我得到的结果是:

Digite o ID: aaaaa
Escreva seu nome:  leo
Digite seu setor(111/112/113): 113
Empty DataFrame
Columns: [NAME, ID, SECTION]
Index: []

我真正想要的是:

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!

你写入新的数据到文件,但这不能改变原来的users_df,你将不得不再次读取它(而不是再次写入)

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) 

或者你应该先添加到users_df,然后保存到to_csv-然后你不必再读一遍。

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)    

register(ID)
# without `to_csv()` and `read_csv()`
current_user = users_df.loc[users_df["ID"] == ID]     
print(current_user) 

相关内容

  • 没有找到相关文章