【发布时间】:2021-08-16 19:00:48
【问题描述】:
在下面的代码中,我从 yfinance 获取了一些数据,然后将其放在文本文件中。为了将其放在文本文件中,我需要将其从字典转换为字符串。当我想读取该文件时,它是一个字符串,但是如果我正确理解了错误消息,我需要它是一个字典。如果有人知道如何解决这个问题,我将不胜感激,谢谢。
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'])
错误信息:
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
【问题讨论】:
-
你可以使用pickle和unpickle。 How can I use pickle to save a dict?
标签: python dictionary text-files yfinance