2015-04-06 110 views
1

我有一個文本文件中的憑據來訪問我的應用程序,它的內容,例如關閉我的文本文件Python,如何替換內容字符串文本的完整行?

#cat /etc/app/paswords 
[email protected] $8324dhedberhnnhdbcdhgvged 
[email protected] $2349cmjedcnecbcdfrfrrf8839 

的空間是標籤的 我想更改密碼散列或完整產品線蒙山新密碼

我有以下代碼:

#cat passreplace.py 
domain = "midomain.com" 
user = "userhappy" 
email = user + "@" + domain 
print email 
if email in open('/etc/app/passwords').read(): 
     print "User already exist!! one moment change your password" 
     #code to remplace password 

謝謝

回答

0

fileinput是這個的不錯選擇。

import fileinput 

email = username + password 

for line in fileinput.input('/etc/app/passwords', inplace=True): 
    if email in line: 
     print("User already exists! Change password now!") 
     username,password = line.split('\t') 
     old_pass = input("Enter old password: ") 
     if old_pass != password: 
      # do something 
     new_pass = input("Enter new password: ") 
     confirm = input("Confirm new password: ") 
     if new_pass != confirm: 
      # do something 
     print("\t".join([email, new_pass]), end="") 
    else: 
     print(line, end="")