如何在已存在的TXT文件中覆盖更新网站密码信息
网站密码管理程序:实现重复网站的密码更新功能
我写了一个能随机生成对应网站密码的Python程序,目前程序会把网站和密码追加写入password.txt文件。现在想实现:当用户再次输入同一个网站(比如Amazon)时,不再重复添加该网站条目,而是更新它对应的旧密码。我学Python才一个月,试了好几种方法都没搞对,当前代码如下:
import random import string # name of website we're creating the password for website = input("What website are you creating a password for? ").capitalize() def char_length(): # makes it so this part will repeat while True: length = input("How many characters would you like your password to be? ") if length.isdigit() and 0 < int(length) < 51: return int(length) else: print('Response must be a number between 0 and 50') def random_pass(length): while True: spec_char = input("Would you like special characters in your password y/n? ").lower() if spec_char == "y": characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for i in range(length)) print("Your password for", website, "is:", password) return password elif spec_char == "n": characters = ''.join(random.choice(string.ascii_letters) for i in range(length)) print("Your password for", website, "is:", characters) return characters else: print("Please only type 'Yes' or 'No'.") random_pass(char_length()) file = open("password.txt", "a+") webname = file.write(website) file.write(": ") new_pass = file.write(random_pass(char_length())) file.write("\n") print(webname) print(new_pass) file.close()
核心思路
要实现更新而非重复添加,关键是先读取文件中已有的网站-密码记录,将其存入字典(网站名作为键,密码作为值),随后用新生成的密码更新字典,最后将字典内容重新写入文件覆盖原有内容。同时修正原代码中重复调用生成密码函数导致用户重复输入的问题。
修改后的代码
import random import string def char_length(): while True: length = input("How many characters would you like your password to be? ") if length.isdigit() and 0 < int(length) < 51: return int(length) else: print('Response must be a number between 1 and 50') def random_pass(length, website): while True: spec_char = input("Would you like special characters in your password y/n? ").lower() if spec_char == "y": characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) print(f"Your password for {website} is: {password}") return password elif spec_char == "n": password = ''.join(random.choice(string.ascii_letters) for _ in range(length)) print(f"Your password for {website} is: {password}") return password else: print("Please only type 'y' or 'n'.") # 获取用户输入 website = input("What website are you creating a password for? ").capitalize() password_length = char_length() new_password = random_pass(password_length, website) # 读取已有密码数据,存入字典 passwords = {} try: with open("password.txt", "r") as f: for line in f: line = line.strip() if not line: continue # 分割网站和密码,兼容密码含冒号的情况(假设网站名不含冒号) web, pwd = line.split(": ", 1) passwords[web] = pwd except FileNotFoundError: # 首次运行文件不存在时,字典保持为空 pass # 更新或添加网站密码 passwords[website] = new_password # 将更新后的字典写入文件 with open("password.txt", "w") as f: for web, pwd in passwords.items(): f.write(f"{web}: {pwd}\n") print("Password saved successfully!")
关键改动说明
- 字典存储数据:将文件中的记录转为字典键值对,可快速完成网站的查找与密码更新,已存在的网站直接覆盖密码,不存在的则新增条目。
- 消除重复输入:原代码两次调用密码生成函数,导致用户重复输入长度和特殊字符选择,现在仅调用一次生成密码,简化交互流程。
- 安全文件操作:使用
with语句自动管理文件的打开与关闭,避免手动关闭可能引发的错误;同时处理文件不存在的异常场景。 - 优化分割逻辑:用
split(": ", 1)分割网站与密码,避免密码中包含冒号时出现分割错误(假设网站名不含冒号,符合常规使用场景)。
内容的提问来源于stack exchange,提问作者phldlphegls1
相关产品推荐
相关产品推荐

