Search code examples
pythondictionarytext-filesyfinance

Converting a dictionary to string, then back to dictionary again


in my code below I get some data from yfinance, then I put it on a text file. In order to put it on a text file I need to convert it from a dictionary to a string. When I want to read in that file it is a string, however I need it to be a dictionary if I've understood the error message correctly. If anybody knows how to fix this I'd greatly appreciate it, thanks.

import finance as yf

x=yf.Ticker("AAPL")
xo=x.info
f = open("atest.txt", "w")
f.write(str(xo))
f.close()
f = open("atest.txt", "r")
info=(f.read())
f.close()
print(info['forwardPE'])

Error Message:

Traceback (most recent call last):
  File "/Users/xox/Desktop/Learning/TextFile/U5.py", line 41, in <module>
    print(info['forwardPE'])
TypeError: string indices must be integers

Solution

  • You should look at the json library if I understand your question, example code to load Json from a file

    import json
    with open('file.txt', 'r') as f:
        data = json.loads(f.read())
    

    Then to write it to a file:

    import json
    data = {"1": "ABC", "2": "DEF"}
    with open('file.txt', 'w') as f:
        f.write(json.dumps(data))