2017-04-18 79 views
1

在bash中,我有一个以变量格式存储我的密码的文件。Python - 从文件中读取变量的值

例如

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) 
+1

[解析文本文件中的键值对]可能的副本(http://stackoverflow.com/questions/9161439/parse-key-value-pairs-in-a-text-file) –

回答

2

阅读文件,并添加检查语句:

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) 
+0

为什么不只是'for在输入行:'? (虽然给'输入'一个不同的名称,所以它没有覆盖内置将是很好的) –

+0

只是为了给一个简单的方法在这里。尽管应该使用不同的名字。 – bhansa

0

你写的东西没有问题。如果你想打高尔夫代码:

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

line = next( line.strip()。split('=')[1]如果你想只输入密码 – Chris

0

我发现这module非常有用!让生活变得更容易。

+1

不要考虑仅在您的解决方案中添加链接,否则容易被删除。 – bhansa