如何检查文本文件中是否已存在输入?
def Database():
file=open("Database.txt","a")
print("Welcome to Database")
name=input("Enter your name\n")
username=input("Enter your username\n")
password=input("Enter your password\n")
date=input("Enter the date\n")
while True:
if username in file():
print("Already exists")
username=input("Enter your username\n")
else:
file.write(name)
file.write("\n")
file.write(username)
file.write("\n")
file.write(password)
file.write("\n")
file.write(date)
file.write("\n")
file.close()
Database()
答案 0 :(得分:1)
由于您需要多次搜索文件,直到客户输入新的用户名,我建议您将其分解为以下步骤:
这会让你感动吗?
答案 1 :(得分:1)
由于您要多次检查,最好将整个列表保存在单行的csv文件中。 这会缩短读取时间。
然后只需检查csv文件中是否有用户名。
添加以下代码段并根据要求进行更改。
import csv
alreadyIn=[]
with open('data.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
alreadyIn.append(row[0])
with open('data.csv', 'w+') as csvfile:
writer = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow([alreadyIn])
with open('data.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
allData = row[0]
if newInput in allData:
#your operations