You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将无格式文本邮件列表转换为Python文件中的列表?

邮箱列表转Python列表:格式修复与代码简化

问题场景

我有一个名为emailListTest.txt的文件,每行存储一个邮箱地址,原本想通过Python代码生成包含这些邮箱的Python列表文件emailListTestList.py,但原代码生成的结果存在格式错误:每个邮箱后带换行符,导致逗号被换行分割。

原代码

emailListFile = open("emailListTest.txt", "r")
emailListFileList = open("emailListTestList.py","w")

print(emailListFileList.write("emailAsList = "))
print(emailListFileList.write("["))

def emailAddressList():
    for i in emailListFile:
        print(emailListFileList.write( "\n'" + i + "'" + ", "))

emailAddressList()

print(emailListFileList.write("]"))

emailListFile.close()
emailListFileList.close()

错误输出

emailAsList = [
'a@a.org
', 
'b@b.org
', 
'c@c.org
', 
'd@d.org
', 
'e@e.org
', 
'f@f.org
', 
'g@g.org
', 
'h@h.org', ]

解决方案

1. 格式问题修复

问题根源是读取每行时,变量i包含了每行末尾的换行符(\n),导致拼接时换行符被保留。解决方法是读取每行后用strip()或rstrip('\n')去除换行符:

  • strip():同时去掉行首行尾的所有空白字符(包括空格、制表符、换行符),适合清理可能带多余空格的邮箱地址。
  • rstrip('\n'):仅去掉末尾的换行符,保留行首可能的空格(邮箱地址一般不会有,但可按需选择)。

2. 代码简化建议

  • 使用with语句自动管理文件上下文,无需手动调用close(),避免资源泄漏。
  • 先将所有邮箱读取并整理成Python列表,再直接将列表格式化为字符串写入文件,无需手动拼接括号、逗号,代码更简洁且格式规范。

优化后的代码

# 用with语句自动处理文件打开/关闭
with open("emailListTest.txt", "r") as email_file, open("emailListTestList.py", "w") as output_file:
    # 读取所有行,去掉换行符和空白,过滤空行
    emails = [line.strip() for line in email_file if line.strip()]
    # 将列表格式化为Python代码字符串写入文件
    output_file.write(f"emailAsList = {emails}\n")

正确输出

emailAsList = ['a@a.org', 'b@b.org', 'c@c.org', 'd@d.org', 'e@e.org', 'f@f.org', 'g@g.org', 'h@h.org']

如果希望输出是每行一个元素的格式化样式,可以修改写入部分:

# 生成每行一个元素的格式
output_file.write("emailAsList = [\n")
for email in emails:
    output_file.write(f"    '{email}',\n")
output_file.write("]\n")

对应的输出:

emailAsList = [
    'a@a.org',
    'b@b.org',
    'c@c.org',
    'd@d.org',
    'e@e.org',
    'f@f.org',
    'g@g.org',
    'h@h.org',
]

内容的提问来源于stack exchange,提问作者Atmosquake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:25:02