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

2024-09-29 21:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

#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

谢谢


Tags: comapp应用程序emaildomainetcpasswordcat
1条回答
网友
1楼 · 发布于 2024-09-29 21:51:31

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="")

相关问题 更多 >

    热门问题