1

In bash, I have a file that stores my passwords in variable format.

e.g.

cat file.passwd
password1=EncryptedPassword1
password2=EncryptedPassword2

Now if I want to use the value of password1, this is all that I need to do in bash.

grep password1 file.passwd  | cut -d'=' -f2

I am looking for an alternative for this in python. Is there any library that gives functionality to simply extract the value or do we have to do it manually like below?

with open(file, 'r') as input:
         for line in input:
             if 'password1' in line:
                 re.findall(r'=(\w+)', line) 
1

3 Answers 3

1

Read the file and add the check statement:

if line.startswith("password1"):
    print re.findall(r'=(\w+)',line)

Code:

import re
with open(file,"r") as input:
    lines = input.readlines()
    for line in lines:
        if line.startswith("password1"):
            print re.findall(r'=(\w+)',line)
Sign up to request clarification or add additional context in comments.

2 Comments

Why not just for line in input:? (Although giving input a different name so it didn't overwrite the built-in would be good)
just to give a simple approach here. although should use different name.
0

There's nothing wrong with what you've written. If you want to play code golf:

line = next(line for line in open(file, 'r') if 'password1' in line)

1 Comment

line = next(line.strip().split('=')[1] for line in open('mout.txt', 'r') if 'password1' in line) if you just want the password returned
0

I found this module very useful ! Made life much easier.

1 Comment

Do not consider adding only links in your solution, there are prone to be removed.