【问题标题】:Listing a single entry by selecting ID and updating a single entry in Python通过选择 ID 并在 Python 中更新单个条目来列出单个条目
【发布时间】: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


【解决方案1】:

您应该从文件中读取 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)

【讨论】:

  • 这个确实有效,输出格式为: (['1\tGeoff\tOwens\t3 Moss Lane\tManchester\tM5 8JL 01384 564877\n']) 如何在没有tbs (\t) 但有实际的制表符空格?我在另一个论坛上读到我应该使用 csv 但这弄乱了我的代码。我真的很感激。
  • 分割线重新加入:print(' '.join(initialise.split()))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 2021-04-08
  • 1970-01-01
相关资源
最近更新 更多