user4889345
user4889345

Reputation:

Python - Read value of variable from file

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) 

Upvotes: 1

Views: 2782

Answers (3)

user4889345
user4889345

Reputation:

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

Upvotes: 0

bhansa
bhansa

Reputation: 7524

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)

Upvotes: 1

Ben Quigley
Ben Quigley

Reputation: 737

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)

Upvotes: 0

Related Questions