如何使用Python对文本文件行切片提取指定服务的账号密码
Python实现密码存储文件内容提取
实现思路
- 统一输入服务名的大小写格式,避免大小写不匹配的问题
- 逐行读取存储文件,过滤空行后匹配对应服务的账号、密码前缀
- 使用仅分割1次的字符串切割方法提取
-后的有效内容,避免账号/密码本身包含-导致切割错误
示例代码
def get_credentials(service_name: str, pwd_file: str = "passwords.txt") -> tuple[str, str]: service_prefix = service_name.upper() username = "" password = "" with open(pwd_file, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue # 匹配账号行 if line.startswith(f"{service_prefix}username-"): username = line.split("-", 1)[1] # 匹配密码行 elif line.startswith(f"{service_prefix}password-"): password = line.split("-", 1)[1] # 账号密码都拿到后可以提前跳出循环 if username and password: break return username, password # 调用测试 if __name__ == "__main__": target_service = input("请输入要查询的服务名:") res_user, res_pwd = get_credentials(target_service) if res_user and res_pwd: print(f"账号:{res_user}") print(f"密码:{res_pwd}") else: print("未找到对应服务的账号密码信息")
注意事项
- 如果你存储的服务名不是全大写格式,删除代码中
.upper()的转换逻辑即可,保持和存储时的命名规则一致 - 如果存储文件中存在同一个服务的多条记录,上述代码会返回第一条匹配到的完整账号密码记录,如需返回最后一条,删除
if username and password: break即可
内容的提问来源于stack exchange,提问作者thefoodiee
相关产品推荐
相关产品推荐

