我有一个文件(mail.txt),其中包含类似的内容
emailfrom = 'satya@gmail.com'
emailto = 'abc@hcl.com','xyz@hcl.com','accc@infy.com'
filepath = 'D:A_2.csv'
subject = 'sells report for xyz'
body = 'hi axx,find the attached file of sells.'
我正在运行一个脚本来发送邮件,在我的脚本中我的消息变量存在emailfrom、emailto、filepath、subject、body。
那么,我如何读取该文本文件,从中读取值,并将变量分配给我的脚本变量呢。
请提出建议。
使用字典来保存信息,使用ast.literal_eval()
来正确评估字符串和tuple
s(否则,到处都会有额外的'
):
import ast
with open('mail.txt') as f:
d = {k:ast.literal_eval(v) for k,v in (line.strip().split(' = ') for line in f)}
然后,您将拥有一个包含每个值的字典:
>>> print(*d.items(), sep='n')
('emailfrom', 'satya@gmail.com')
('emailto', ('abc@hcl.com', 'xyz@hcl.com', 'accc@infy.com'))
('filepath', 'D:\A_2.csv')
('body', 'hi axx,find the attached file of sells.')
('subject', 'sells report for xyz')
访问您期望的值:
>>> d['subject']
'sells report for xyz'
objFile = open("youfile.txt", "r")
lsFileContents = objFile.readlines()
strEmailFrom = lsFileContents[0].strip().split("=")[1].strip()
strEmailTo = lsFileContents[1].strip().split("=")[1].strip()
strFilePath = lsFileContents[2].strip().split("=")[1].strip()
strBody = lsFileContents[4].strip().split("=")[1].strip()
strSubject = lsFileContents[3].strip().split("=")[1].strip()
objFile.close()