从文本文件到列表框Python的偶数行

2024-09-28 19:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户名密码登录系统,想添加一个删除用户功能。用户名存储在文本文件的偶数行(inc zero),密码存储在奇数行。有没有办法只把偶数行添加到一个列表框中,通过curselection将要删除的行显示密码将与点相反。我目前有文本文件的所有内容显示在列表框中,但只想显示用户名。为了删除行,我在从列表框中删除所选行之后,将列表框的内容复制到一个新的文本文件中。在选择要删除的用户名后,是否还有方法删除相应的密码?在

def DelUser():

    global rootDU
    global listbox

    rootDU = Tk()
    rootDU.title('Delete user')

    users = open(creds, 'r')
    mylist = users.readlines()
    users.close()

    listbox = Listbox(rootDU, width=50, height=6)
    listbox.grid(row=0, column=0)
    yscroll = Scrollbar(command=listbox.yview, orient=VERTICAL)
    yscroll.grid(row=0, column=1, sticky=N + S)
    listbox.configure(yscrollcommand=yscroll.set)

    enter1 = Label(rootDU, text='Click on the user to delete', width=50)
    enter1.grid(row=1, column=0)

    for item in mylist:
        listbox.insert(END, item)

    delButton = Button(rootDU, text='Delete', command=RemoveUser)
    delButton.grid(columnspan=2, sticky=W)
    delButton.grid(row=2, column=0)

def RemoveUser():

    global listbox

    try:
        index = listbox.curselection()[0]
        listbox.delete(index)
        os.remove(creds)
        newfile = 'tempfile.txt'
        with open(newfile, 'w') as f:
            f.write(''.join(listbox.get(0, END)))
            f.close()

    except IndexError:
        pass

Tags: 密码columnglobalusers用户名gridrow偶数
1条回答
网友
1楼 · 发布于 2024-09-28 19:28:56

只需在列表框中每隔一行添加一行:

for item in mylist[::2]:
    listbox.insert(END, item)

::2片从第0行开始每隔一行拾取一次。有关详细信息,请参见Explain Python's slice notation。在

但是,您仍然需要重新读取文件以找到相应的密码,因为您不单独存储这些信息。您确实希望存储一个从用户名到密码的映射(单独存储,作为DelUserRemoveUser之间共享的信息),这样就可以轻松地用剩余的用户和密码重新编写用户文件。在

您还可以考虑对文件使用不同的格式;在同一行中写入用户名和密码,但在它们之间加上分隔符,这样可以更容易地处理数据。在

相关问题 更多 >