1

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
Faiz
  • 143
  • 1
  • 10

3 Answers3

1

You can use json.dump and json.loads for this purpose. before saving, you can convert any object into string using json.dump. when loading, you can use json.loads.

Below is the pseudo code

import json
str = json.dump(obj)
...
obj = json.loads(str)
...
TopW3
  • 1,477
  • 1
  • 8
  • 14
1

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))
Quintin
  • 125
  • 6
1

I think the most common way to do en/decode object to/from string is the use of JSON. there is a standard json module in python. What you have to do is just to import json and call json.dump and json.loads