在我下面的代码中,我从 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
答案 0 :(得分:1)
您可以为此使用 json.dump 和 json.loads。在保存之前,您可以使用 json.dump 将任何对象转换为字符串。加载时可以使用json.loads。
下面是伪代码
import json
str = json.dump(obj)
...
obj = json.loads(str)
...
答案 1 :(得分:1)
如果我理解您的问题,您应该查看 json 库,从文件加载 Json 的示例代码
import json
with open('file.txt', 'r') as f:
data = json.loads(f.read())
然后将其写入文件:
import json
data = {"1": "ABC", "2": "DEF"}
with open('file.txt', 'w') as f:
f.write(json.dumps(data))
答案 2 :(得分:1)
我认为在字符串中对对象进行编码/解码的最常用方法是使用 JSON。 python中有一个标准的json模块。你要做的只是导入json并调用json.dump和json.loads