python - 使用文本文档更改列表中的项目

标签 python python-3.x list function tkinter

我遇到一个问题,我正在运行一个函数,该函数应该检查文本文档中的行,找到匹配的用户名,并在每行中更改列表中的第二个sintem(它是一个密码重置程序)。文本文档通常如下所示:

test test
username password
hello hi

这是我尝试过的代码。登录时使用了reset_username。(例如,我还包含了登录功能)

密码修改功能:

def password_change():
    for _ in open('info.txt', 'r').readlines():
        login_info = _.split()
        if reset_username == login_info[0]:
            login_info[1] = [password_reenter_txt.get()]
            menu_window()

登录功能:

def txt_file_log_in():

    try:
        for _ in open('info.txt', 'r').readlines():
            login_info = _.split() #split on the space made and store result with 2 strings
            if username_enter_txt.get() == login_info[0] and password_enter_txt.get() == login_info[1]:
                password_fault_report.configure(text='User name and Password Correct')

                global reset_username
                reset_username = username_enter_txt.get()

                messagebox.showinfo('Success', 'You have successfully logged in!')#pop up window informing user for sign up.
                login_window.destroy()
                final_window()

        password_fault_report.configure(text='User name or password incorrect,')

    except:
        password_fault_report.configure(text='No accounts found, you need to sign in first...')

我遇到的错误是它将运行该函数并运行菜单窗口,但它根本不会更改文档。

我是 tk、python 的初学者,所以这可能是一个非常愚蠢的错误,所以很抱歉。另外,如果 iv'e 在帖子中犯了错误,也请告诉我:)

最佳答案

open 语句中的值'r' 允许您“只读”该文件。为了写入文件,您需要使用 'w' 但请记住,这将写入文件并删除之前存在的所有内容,因此我们要确保将所有内容写回到文件中.

我们可以通过使用列表来存储所有值并根据需要进行更新来实现此目的。

示例代码:

def password_change(reset_username, password_reenter_txt):
    # Create empty list to hold file data.
    login_info = []
    with open('some_file', 'r') as data:
        for _ in data.readlines():
            login_info.append(_.split())
    print(login_info)
    # Check values in list and update if condition true.
    for sub_list in login_info:
        if len(sub_list) > 0:
            if reset_username == sub_list[0]:
                sub_list[1] = password_reenter_txt

    # write new values of list to file if previous condition met.
    with open('some_file', 'w') as data:
        for sub_list in login_info:
            if len(sub_list) > 0:
                data.write('{} {}\n'.format(sub_list[0], sub_list[1]))


for i in range(9):
    password_change('name' + str(i+1), 'pass')

# Check new values in file.
with open('some_file', 'r') as data:
    for _ in data.readlines():
        print(_.strip('\n'))

使用的测试文件数据:

name1 pass1
name2 pass1
name3 pass1
name4 pass1
name5 pass1
name6 pass1
name7 pass1
name8 pass1
name9 pass1

结果:

name1 new_pass
name2 new_pass
name3 new_pass
name4 new_pass
name5 new_pass
name6 new_pass
name7 new_pass
name8 new_pass
name9 new_pass

关于python - 使用文本文档更改列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60307353/

相关文章:

python - ChromeDriver 可执行文件需要在路径中可用

python-3.x - ValueError : Importing a SavedModel with tf. saved_model.load 需要 'tags=' 参数

java - Android arraylist 因迭代而崩溃

java - 更正 Book 类以获取 getBooksByAuthor 方法的输出

python - 在 Python 3 中使用 BeautifulSoup 抓取 URL

python - 通过在文件内进行数学运算来编辑文本文件

python - 如何根据列标签获取数据帧的集合差异?

python-3.x - Python3中的异常处理

python - 将 16 支队伍中的随机队伍分配给 8 人中的随机人员

python - 在特定行和列中替换 csv python 中的特定字符串