如何用Python从文本文件中逐行提取邮箱和密码
逐行提取邮箱和密码的实现方案
你的现有代码存在两个问题:一是直接按索引取的是整行文本,没拆分出邮箱和密码;二是没有实现“依次提取下一行”的逻辑,需要加个计数器跟踪当前读取位置。
以下是基于类结构的完整实现,能完美满足你的需求:
class AccountLoader: def __init__(self): # 存储拆分后的邮箱和密码对 self._accounts = [] # 读取文件(注意改成你实际的文件名,比如myfile.txt或accounts.txt) with open("./myfile.txt", "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue # 跳过空行 # 只分割第一个冒号,避免密码里带冒号导致拆分错误 parts = line.split(":", 1) if len(parts) == 2: email, password = parts self._accounts.append((email.strip(), password.strip())) else: print(f"跳过无效行: {line}") # 初始化当前读取位置的索引 self._current_idx = 0 def get_next_email(self): """获取下一行的邮箱,无剩余账号时返回None""" if self._current_idx < len(self._accounts): email = self._accounts[self._current_idx][0] self._current_idx += 1 return email return None def get_next_password(self): """获取当前对应行的密码(需先调用get_next_email,保证同步)""" if self._current_idx > 0 and self._current_idx - 1 < len(self._accounts): return self._accounts[self._current_idx - 1][1] return None # 可选:提供一次性获取邮箱和密码的方法,更便捷 def get_next_account(self): """同时获取下一行的邮箱和密码,无剩余时返回(None, None)""" if self._current_idx < len(self._accounts): email, password = self._accounts[self._current_idx] self._current_idx += 1 return email, password return None, None
使用示例
# 创建加载器实例 loader = AccountLoader() # 方式1:分开调用提取邮箱和密码 while True: email = loader.get_next_email() if not email: break password = loader.get_next_password() print(f"邮箱: {email}, 密码: {password}") # 方式2:一次性获取(更简洁) loader2 = AccountLoader() while True: email, password = loader2.get_next_account() if not email: break print(f"邮箱: {email}, 密码: {password}")
关键细节说明
- 用
with open语句自动关闭文件,避免资源泄漏 - 用
split(":", 1)只拆分第一个冒号,兼容密码含冒号的情况 - 维护
_current_idx变量跟踪读取位置,实现依次提取的逻辑 - 增加了空行、无效行的处理,避免程序出错
内容的提问来源于stack exchange,提问作者Jane1990
相关产品推荐
相关产品推荐

