2017-04-18 19 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