【问题标题】:Appending a line in a file to a variable将文件中的一行附加到变量
【发布时间】:2017-11-29 00:55:23
【问题描述】:

我需要在文件中搜索用户名(用户名存储在名为 x 的变量中),如果 x 与文件中的一行匹配,则将该行恰好在其下方 2 行追加到另一个变量(将被称为 y )。我该怎么做?

我对此很陌生,无法访问我的原始代码。我已经记住了文件的代码和内容,由于我没有经验,所以它非常简单:

文件内容示例:

Steven Abbot
qwerty
london

代码示例:

x = input(“Enter name:”)
password = (“Enter password:”)
city = (“Enter city name”)
crd = open(“credentials.txt”, “a”)
crd.write(x)
crd.write(\n)
crd.write(password)
crd.write(\n)
crd.write(city)
crd.write(\n)
crd.close()

请注意,这个程序要多次使用,所以我不能简单地将第三行附加到 y。城市名称是我需要提取并附加到名为 y 的变量的信息。我被卡住了,因为城市名称可能因用户而异,而且我不知道如何选择名称下方的 2 行。

对于文件的示例内容,y 最终会包含“london”,因为它在 x 下面两行。

【问题讨论】:

  • 您好!你能粘贴你的源文件和你写的python文件,以便我们看到你卡在哪里吗?
  • 我已经编辑并包含了代码,虽然它没有什么特别之处,当然可以使用改进。目前我只关心我描述的任务
  • 您能否展示您想要的输出以及您目前得到的结果?
  • 目前我不需要输出,因为我只想附加到一个名为 y 的变量。由于我不知道如何解决这个问题,我希望在这里将任何答案应用于我已经得到的答案。我所展示的就是我所拥有的。

标签: python file search append


【解决方案1】:

试试这个:

def get_password(name, filename):
    textfile = file(filename)
    found = False
    skip = 0 
    for line in textfile :
        if found == False            
            if line == name:
                found = True  
        else
            skip = skip + 1
            if skip == 2
                return line

    return None # if name not found or password not found return  None

然后调用:

get_password(x, “credentials.txt”)

【讨论】:

    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 2012-01-20
    • 2014-03-17
    • 1970-01-01
    • 2021-02-15
    • 2019-11-23
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多