通过选择 ID 列出单个条目并更新 Python 中的单个条目
Listing a single entry by selecting ID and updating a single entry in Python
我正在创建一个程序,我将在 bash/terminal 中 运行。当 运行 时,程序应该提示用户“请添加用户 ID”的问题。输入 ID(不是索引)后,它应该显示 selected ID。例如:1 应该显示整行 Will Smith.
我实现的代码如下,但它显示了索引。如果我 select 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()
谢谢
您应该从文件中读取 ID。
def show_single_user():
initialise = []
input_user_id = input("Please add user index.")
for line in open("file.txt"):
id = line.split()[0]
if id == input_user_id:
initialise.append(row)
print(initialise)
我正在创建一个程序,我将在 bash/terminal 中 运行。当 运行 时,程序应该提示用户“请添加用户 ID”的问题。输入 ID(不是索引)后,它应该显示 selected ID。例如:1 应该显示整行 Will Smith.
我实现的代码如下,但它显示了索引。如果我 select 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()
谢谢
您应该从文件中读取 ID。
def show_single_user():
initialise = []
input_user_id = input("Please add user index.")
for line in open("file.txt"):
id = line.split()[0]
if id == input_user_id:
initialise.append(row)
print(initialise)