Search code examples
python-3.xstringpasswordsarea

Read specific area or string in a text file


I have a text file I have written user data to. Username, E-Mail and Password.

That's how the userfile looks like for now

[<< LOGIN >>]

Username: admin

Password: 12345678

E-Mail: hue@hue.hue

[<< LOGIN END >>]

Now for the question.

How can I tell python to specifically read the password only? I mean, it may be possible for now that we know what the password is and what its lenght is. But how am I supposed to read the password later when I encrypt it and get some gibberish with 30+ characters?


Solution

  • The line will contain password so just split once and get the second element:

    In [20]: from simplecrypt import encrypt
    
    In [21]: ciph = encrypt('password', "12345678")
    
    In [22]: line = "Password: " + ciph
    
    In [23]: line
    Out[23]: 'Password: sc\x00\x01\x0cP\xa1\xee\'$"\xc1\x85\xe0\x04\xd2wg5\x98\xbf\xb4\xd0\xacr\xd3\\\xbc\x9e\x00\xf1\x9d\xbe\xdb\xaa\xe6\x863Om\xcf\x0fc\xdeX\xfa\xa5\x18&\xd7\xcbh\x9db\xc9\xbeZ\xf6\xb7\xd3$\xcd\xa5\xeb\xc8\xa9\x9a\xfa\x85Z\xc5\xb3%~\xbc\xdf'
    
    In [24]: line.split(None,1)[1]
    Out[24]: 'sc\x00\x01\x0cP\xa1\xee\'$"\xc1\x85\xe0\x04\xd2wg5\x98\xbf\xb4\xd0\xacr\xd3\\\xbc\x9e\x00\xf1\x9d\xbe\xdb\xaa\xe6\x863Om\xcf\x0fc\xdeX\xfa\xa5\x18&\xd7\xcbh\x9db\xc9\xbeZ\xf6\xb7\xd3$\xcd\xa5\xeb\xc8\xa9\x9a\xfa\x85Z\xc5\xb3%~\xbc\xdf'
    
    In [25]: decrypt("password",line.split(None,1)[1])
    Out[25]: '12345678'
    
    In [26]: "12345678" == decrypt("password",line.split(None,1)[1])
    Out[26]: True
    

    When you iterate over the file simple use if line.startswith("Password")...

    with open(your_file) as f:
        for line in f:
           if line.startswith("Password"):
                password = line.rstrip().split(None,1)[1]
                # do your check
    

    You could use a dict and pickle using passwordas a key then just do a lookup: