【发布时间】:2020-07-01 08:30:49
【问题描述】:
我正在创建一个将在 bash/终端中运行的程序。运行时,程序应该提示用户“请添加用户 ID”的问题。输入 ID(不是索引)后,应显示所选 ID。例如:1 应该显示 Will Smith 的整行。
我实现的代码如下,但它显示了索引。如果我选择 1,它将显示 Jane Doe 的行。我哪里错了?:
def show_single_user():
initialise = []
input_user_id = input("Please add user index.")
for i, row in enumerate(open("file.txt")):
if str(i) in input_user_id:
initialise.append(row)
print(initialise)
当我想删除用户 ID 时,我遇到了类似的问题,它会随机删除用户而不是请求的 ID。我不想根据从零开始的索引进行删除。下面是代码。
def delete_user_id():
text_file = open("file.txt", "r")
target_id = text_file.readlines()
text_file.close()
user_input = input("Add the ID to delete:")
del target_id[1]
new_file = open("file.txt", "w+")
# For loop iterating to delete the appropriate line
for line in target_id:
new_file.write(line)
new_file.close()
print("User ID successfully removed!")
input("Press any key to return to main menu")
delete_user_id()
谢谢
【问题讨论】:
-
在您的第一个代码中,sn-p
str(i)是文件行枚举的索引,它从零开始,而不是 1。因此,如果您输入 1,您实际上会得到索引为 1 的行是第二行。 -
您可能必须使用
for-loop 来搜索在第一列中具有预期 ID 的行。或者也许用pandas加载它,然后你可以更轻松地工作。
标签: python csv file text user-input