检查文本文件中是否存在变量字符串

时间:2020-07-07 21:20:53

标签: python text replace txtextcontrol

所以,伙计们,我试图制造一个密码生成器,但是我遇到了麻烦:

首先,我用于测试的代码:

idTest= "TEST"
passwrd= str(random.randint(11, 99))


if not os.path.exists('Senhas.txt'):
    txtFileW = open('Senhas.txt', 'w')
    txtFileW.writelines(f'{idTest}: {passwrd}\n')
    txtFileW.close()
else:
    txtFileA = open('Senhas.txt', 'a')
    txtFileA.write(f'{idTest}: {passwrd}\n')
    txtFileA.close()

print(f'{idTest}: {passwrd}')

好吧,我期望的是这样的:

else:
    with open('Senhas.txt', 'r+') as opened:
        opened.read()
        for lines in opened:
            if something == idTest:
                lines.replace(f'{something}', f'{idTest}')
            else:
                break
txtFileA = open('Senhas.txt', 'a')
txtFileA.write(f'{idTest}: {passwrd}\n')
txtFileA.close()

print(f'{idTest}: {passwrd}')

我已经搜索了它,但是我发现的所有方法都是将其分成2个文件(对于我的项目,它不匹配)或使用“静态”字符串,这对我也不匹配。

1 个答案:

答案 0 :(得分:0)

您可以使用fileinput模块来更新文件。

import fileinput

with fileinput.input(files=('Senhas.txt'), inplace=True) as f:
    for line in f:
        if (line.startswith(idTest+':'):
            print(f'{idTest}: {passwrd}')
        else:
            print(line)
相关问题