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
    Possible duplicate of [Parse key value pairs in a text file](http://stackoverflow.com/questions/9161439/parse-key-value-pairs-in-a-text-file) – Darrick Herwehe Apr 18 '17 at 14:28

3 Answers3

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)
bhansa
  • 7,282
  • 3
  • 30
  • 55
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)
Ben Quigley
  • 727
  • 4
  • 18
  • line = next(line.strip().split('=')[1] for line in open('mout.txt', 'r') if 'password1' in line) if you just want the password returned – Chris Apr 18 '17 at 14:19
0

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