Guest = {}
with open('LogIn.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for username,password in credentials:
Guest[username] = password
def DelUser():
DB = open('LogIn.txt',"r+")
username = DB.read()
delete = raw_input("Input username to delete: ")
if delete in username:
<insert code to remove line containing username:password combination>
所以,我有一个LogIn.txt文件,其中包含以下用户名:密码组合:
chris:test
char:coal
yeah:men
test:test
harhar:lololol
我想在对象“删除”中删除我想要的用户名:密码组合 但问题是,如果我使用
if delete in username:
论点,它也必须考虑密码。例如,如果我有两个帐户使用相同的密码怎么办?或者像上面那样。我可以采取什么样的路径?或者我在这里遗漏了什么?
答案 0 :(得分:0)
使用
if delete in Guest:
测试delete
中的Guest
是否为Guest
。由于if delete in Guest
的密钥代表用户名,delete
会测试import fileinput
import sys
def DelUser(Guest):
delete = raw_input("Input username to delete: ")
for line in fileinput.input(['LogIn.txt'], inplace = True, backup = '.bak'):
if delete not in Guest:
sys.stdout.write(line)
是否为用户名。
您可以使用fileinput模块重写“inplace”文件:
{{1}}
答案 1 :(得分:0)
根据您当前的DelUser功能,您可以读取该文件,删除以用户删除的行,并写一个新文件:
def DelUser():
# read the current files, and get one line per user/password
with open('LogIn.txt',"r+") as fd:
lines = fd.readlines()
# ask the user which one he want to delete
delete = raw_input("Input username to delete: ")
# filter the lines without the line starting by the "user:"
lines = [x for x in lines if not x.startswith('%s:' % delete)]
# write the final file
with open('LogIn.txt', 'w') as fd:
fd.writelines(lines)