2015-04-06 112 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="")