Search code examples
pythontextreplacetxtextcontrol

Check if a variable string exist in a text file


So guys, i'm tryng to make a password generator but i'm having this trouble:

First, the code i use for tests:

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}')

Well, what i'm expecting is something like this:

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}')

I've searched for it but all i've found are ways to separate it in 2 files (for my project it doesn't match) or with "static" strings, that doesn't match for me as well.


Solution

  • You can use the fileinput module to update the file in place.

    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)