Search code examples
pythonobjectplaintext

Read plain python object from file


Our client provided us with text files containing the following data:

{'op-code-gtm-gtm2-count': {'Label': 'op-code-gtm-gtm2-count', 'Datapoints': [{'Timestamp': datetime.datetime(2018, 12, 25, 17, 10, tzinfo=tzlocal()), 'Sum': 79792.0,....

Note that it's a default python object, and not a json one (else we'd be using json.load(file)).
Any suggestions on how we could create a python object from reading this file ?


Solution

  • A friend suggested this solution:

    import datetime
    from tzlocal import get_localzone as tzlocal
    
    with open('myfile.txt') as f:
       st = f.read()
       data = eval(st)
    

    Hope this helps!