Python 程序:合并邮件
在此程序中,您将学习将邮件合并为一个。
要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:
当我们想将相同的邀请发送给许多人时,邮件的正文不会更改。 仅名称(可能还有地址)需要更改。
邮件合并是执行此操作的过程。 我们没有单独编写每封邮件,而是为邮件正文提供了模板,并通过名称列表将它们合并在一起以形成所有邮件。
合并邮件的源代码
# Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt",'r',encoding = 'utf-8') as names_file: # open body.txt for reading with open("body.txt",'r',encoding = 'utf-8') as body_file: # read entire content of the body body = body_file.read() # iterate over names for name in names_file: mail = "Hello "+name+body # write the mails to individual files with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file: mail_file.write(mail)
对于此程序,我们将所有名称写在文件"names.txt"中的不同行中。 正文位于"body.txt"文件中。
我们以读取模式打开两个文件,并使用for循环遍历每个名称。 创建了一个名为"name.txt"的新文件,其中name是该人的名字。
我们使用strip()方法清除前导和尾随空格(从文件中读取一行还读取换行符'\n')。 最后,我们使用write()方法将邮件的内容写入此文件。
了解更多有关 Python 中文件的信息。