首页 > 解决方案 > 从 Python 中的文本文件中读取选定的条目

问题描述

只是为了好玩,我正在制作一个程序,我可以在其中将所有帐户登录名和密码添加到文本文件中。它有四个可以运行的主要任务:

我知道如何添加条目,但我不知道如何从文本文件中查看单个条目。

它在我的文本文件中的顺序是:服务、用户名、密码

这是我的代码:

def Add():
   service = input(str("What is the service?\n>")
   username = input(str("What is the username of this entry?\n")
   password = input(str("Please input the password of this entry")
   entry = str("\n" + service + "-" + username + "," + password)
   f = open("Logins.txt", "a")
   f.write(entry)
   f.close()
   check = input(str("Your entry has been saved\n"))
   time.sleep(3)

代码的图像

标签: python

解决方案


首先,我会将文本文件更改为更好的格式,例如 CSV。为此,请将“-”分隔符更改为逗号。另外,使用 python csv 库来执行操作。

然后,添加一个新选项到“显示列表”或类似的调用这样的函数的东西:

def view():
    csvfile = open('Logins.txt', 'rb')
    row_num = 1
    csvFileArray = []
    print("Select a row number to view:\n")
    for row in csv.reader(csvfile, delimiter=',') 
        print(str(row_num) + ") " + row[0] + " " + row[1] ... + "\n")
        # insert all rows (lines) from the csv file into a python array
        csvFileArray.append(row)
        row_num += 1

    my_row_choice = input(str("Row number: \n")
    my_row_choice = int(my_row_choice)
    # since arrays are 0-indexed, take the number presented to the user and subtract 1
    # then, the rows are represented by array elements within each line, so we display like csvFileArray[my_row_num-1][0] for service, etc.
    print("Service: " + csvFileArray[my_row_choice-1][0] + " Username: " + csvFileArray[my_row_choice-1][1] + " Password: " + csvFileArray[my_row_num-1][2])

您所要做的就是向用户提供他们可以选择的选项列表,并根据他们的选择调用适当的功能(例如调用 的“显示列表”view()等)。

这只是我的想法,但它应该让你开始。还有其他方法可以提取特定行而不必遍历整个文件,但这应该可以完成您想要的基本操作。

可以在此处找到 csv 库的更多信息: https ://docs.python.org/3/library/csv.html


推荐阅读