python - 在 Python 中将 Excel 或 CSV 文件转换为电子邮件地址列表

标签 python excel pandas csv openpyxl

我有一些 Python 经验,但我不是专家,所以这里请放轻松。

我有一个 Python 脚本,可以全天向人们发送自动电子邮件报告。现在,电子邮件地址全部存储在脚本本身中,但我希望将电子邮件地址存储在外部文件中,其他人可以编辑接收它们的人,而无需打开脚本本身。脚本中有不同的电子邮件列表,我正在努力弄清楚如何将其转换为文件。

例如,这些可能是三个电子邮件列表,因为它们将存储在 Python 中:

Group_A = ['ABC@yahoo.com', 'def@gmail.com']

Group_B = ['xyz@yahoo.com', tuv@gmail.com']

Group_C = ['hij@yahoo.com', klm@gmail.com']

如何将它们存储在外部文件中并让 Python 将它们作为单独的列表读取?

我可以使用 Excel(通过 Openpyxl 或 Pandas 读取)或 CSV 甚至 txt 文档,但是让 Python 读取文件并将电子邮件地址存储在自己的列表中的最佳方法是什么?列表的名称还需要在文件中设置,因为每个列表都会根据其名称收到单独的电子邮件。

最佳答案

如果您将电子邮件放入这样的简单文本文件中:

$ cat emails.txt
foo
bar
baz

你可以像这样将它读入Python:

emails = []

with open("emails.txt") as f:
    for line in f:
        if len(line.strip()) > 0:
            emails.append(line.strip())

print(emails)

结果将如下所示:

['foo', 'bar', 'baz']

what is the best way to get Python to read the file and store the email addresses in their own lists? The name of the list also needs to be set in the file as each list gets a separate email depending on what the name of it is.

我只需将每组电子邮件保存到不同的文件中,然后将该文件的内容读取到您需要的列表中。

文件:

$ cat group_a.txt
ABC@yahoo.com
def@gmail.com

$ cat group_b.txt
xyz@yahoo.com
tuv@gmail.com

$ cat group_c.txt
hij@yahoo.com
klm@gmail.com

将它们读入 Python 列表:

def readlines(file):
    lines = []
    with open(file) as f:
        for line in f:
            if len(line.strip()) > 0:
                lines.append(line.strip())
    return(lines)

Group_A = readlines("group_a.txt")
print(Group_A) # ['ABC@yahoo.com', 'def@gmail.com']

Group_B = readlines("group_b.txt")
print(Group_B) # ['xyz@yahoo.com', 'tuv@gmail.com']

Group_C = readlines("group_c.txt")
print(Group_C) # ['hij@yahoo.com', 'klm@gmail.com']

关于python - 在 Python 中将 Excel 或 CSV 文件转换为电子邮件地址列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286236/

相关文章:

python - 如何使用 python 计算文本文件中的数字列表

python - 为什么 pymongo 需要 sudo 进行 pip 安装?

c# - SpreadsheetGear 在构造函数内抛出 IndexOutOfRangeException

arrays - TRANSPOSE 公式数组

python - 从重新采样的数据框中一次选择一个日期

python - pandas roll_apply 处理 pandas.TimeGrouper 等对象类型

python - Django 1.8.2 不提供所有静态文件 - django-pipeline

python - 无法将 iPython 设置为使用 2.6.1 Python

c# - EPPlus AddPicture 导致 Excel 2007 文件损坏

python - 合并 Pandas 中的几个数据透视表