在文件中添加一行到变量

时间:2017-11-29 00:55:24

标签: python file search append

我需要在文件中搜索用户名(用户名存储在名为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下面的两行。

1 个答案:

答案 0 :(得分: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”)