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

Convert Excel or CSV file into lists of email addresses in Python

我对 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']