python - 从 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)
解决方案
首先,我会将文本文件更改为更好的格式,例如 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
推荐阅读
- python - 在简单的电子商务数据库中创建 OrderItem 或将 LineItem 链接到 Order?
- ios - 从像素阵列生成图像(快速)
- java - 如何处理连接到仅由服务层/业务逻辑使用的数据库?
- php - 在php中登录adobe connect的api请求
- javascript - 请求 React 组件执行渲染以外的操作
- django - 如何验证 django 静态文件访问?
- visual-studio - 在 Visual Studio 2019 中创建文件时是否可以自动选择文件名?
- docker - 在基于 Debian 的 docker 镜像中安装 Java 运行时
- flutter - 如何在颤动中制作具有多种颜色的ColorTween动画
- c# - 如何使用 Roslyn Analyzer 检测特定方法是否不包含 try catch 块?