read a file(.txt,.csv..xls) and assign them to respective variable in python script
Question: i have a file(mail.txt) and that have content like

    
    
     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.'
    

And i am running a script to send mail and in my script my msg variables
emailfrom,emailto,filepath,subject,body are present.

So how can i read that text file and read values from there and assign
variables to my script variables.

please suggest.


Answer: Use a dictionary to hold the information, with `ast.literal_eval()` to
properly evaluate your strings and `tuple`s (or else you would end up with
extra `'` everywhere):

    
    
    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)}
    

You will then have a dictionary holding each value:

    
    
    >>> 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')
    

Access the values as you would expect:

    
    
    >>> d['subject']
    'sells report for xyz'
    

