Python,如何替换包含字符串文本的完整行?

时间:2015-04-06 04:12:23

标签: python python-2.7 python-3.x

我有一个文本文件,其中包含访问我的应用程序的凭据,例如关闭我的文本文件

#cat /etc/app/paswords
petter@domain.com    $8324dhedberhnnhdbcdhgvged
userhappy@domain.com    $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

谢谢

1 个答案:

答案 0 :(得分: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="")