Python - 从文件中读取变量的值

时间:2017-04-18 14:12:03

标签: python

在bash中,我有一个以可变格式存储密码的文件。

e.g。

cat file.passwd
password1=EncryptedPassword1
password2=EncryptedPassword2

现在,如果我想使用password1的值,这就是我需要在bash中做的所有事情。

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

我在python中寻找替代方法。是否有任何库提供简单提取值的功能,或者我们必须手动执行此操作  如下?

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

3 个答案:

答案 0 :(得分:1)

阅读文件并添加检查声明:

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

<强>代码

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)

答案 1 :(得分:0)

你所写的内容没有错。如果你想玩代码高尔夫:

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

答案 2 :(得分:0)

我发现这个module非常有用!让生活更轻松。

相关问题