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

Check if a variable string exist in a text file

伙计们,我正在尝试制作一个密码生成器,但遇到了这个问题:

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

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 个文件(对于我的项目不匹配)或使用“静态”字符串的方法,这对我来说不匹配嗯

您可以使用 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)