
本文介绍如何使用python脚本高效地将包含500+行“email:password”格式的纯文本文件,自动转换为结构清晰、缩进规范的json数组文件,避免手动处理错误,提升数据格式化效率。
本文介绍如何使用python脚本高效地将包含500+行“email:password”格式的纯文本文件,自动转换为结构清晰、缩进规范的json数组文件,避免手动处理错误,提升数据格式化效率。
在日常数据处理中,常会遇到以简单分隔符(如冒号 :)存储的账号凭证文本,例如每行形如 user@example.com:SecurePass123。当条目数量达数百甚至上千时,手动转为JSON不仅耗时,还极易出错。此时,编写轻量级Python脚本是最可靠、可复用的解决方案。
以下是一个健壮、易用的转换脚本,支持逐行解析、字段校验与格式化输出:
import json
def convert_txt_to_json(input_file: str, output_file: str = "result_list.json"):
json_list = []
try:
with open(input_file, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line: # 跳过空行
continue
if ':' not in line:
print(f"警告:第 {line_num} 行缺少 ':' 分隔符,已跳过 → '{line}'")
continue
parts = line.split(':', 1) # 仅按第一个冒号分割,避免密码含冒号时出错
email = parts[0].strip()
password = parts[1].strip()
if not email or not password:
print(f"警告:第 {line_num} 行邮箱或密码为空,已跳过 → '{line}'")
continue
json_list.append({
"Email": email,
"Password": password
})
# 写入JSON文件(UTF-8编码 + 4空格缩进)
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(json_list, f, indent=4, ensure_ascii=False)
print(f"✅ 成功转换 {len(json_list)} 条记录,已保存至 '{output_file}'")
except FileNotFoundError:
print(f"❌ 错误:找不到输入文件 '{input_file}',请确认路径是否正确。")
except Exception as e:
print(f"❌ 处理过程中发生异常:{e}")
# 使用示例(请将 'accounts.txt' 替换为你的实际文件名)
convert_txt_to_json("accounts.txt")
? 关键说明与注意事项:
Miller (mlr) 是一个命令行工具,用于查询、整形和重新格式化名称索引数据,如 CSV、TSV、JSON 和 JSON Lines。它将 awk、sed、cut、join 和 sort 的功能整合到一个专为结构化数据处理而构建的单一工具中。
- ✅ 安全分割:使用
split(':', 1)确保即使密码中含冒号(如pass:word123),也能正确提取邮箱与密码; - ✅ 容错处理:自动跳过空行、缺失分隔符或字段为空的异常行,并给出明确提示;
- ✅ 编码兼容:显式指定
utf-8编码,避免中文邮箱或特殊字符乱码; - ✅ JSON可读性:
indent=4和ensure_ascii=False保证输出为人类可读格式,且保留 Unicode 字符(如 emoji 或中文); - ⚠️ 重要提醒:请勿将含真实密码的 JSON 文件上传至公开仓库或未加密环境;建议转换后立即对敏感文件进行访问权限管控或加密处理。
运行脚本前,只需将你的原始文本文件(如 accounts.txt)与脚本置于同一目录,修改函数调用中的文件名即可。执行完成后,你将获得一个符合 RFC 8259 标准、可被任意编程语言直接解析的 JSON 数组文件。










