+
95
-

如何在 Python 中将变量保存到文件然后读取?

如何在 Python 中将变量保存到文件然后读取?


网友回复

+
15
-

1、使用repr

dict1 = {"one" : 1, "two" : 2}
file = open("Python.txt", "w")
str = repr(dict1)
file.write("dict1 = " + str)
file.close()
#读取

# 打开文件以读取内容
with open("Python.txt", "r") as file:
    content = file.read()

# 创建一个空的字典,准备存储读取到的变量
read_dict = {}

# 使用 exec() 执行文件中的代码
exec(content, read_dict)

# 从 read_dict 中获取读取到的字典
saved_dict = read_dict['dict1']

# 输出读取到的字典
print(saved_dict)

2、格式化

dict1 = {"one" : 1, "two...

点击查看剩余70%

我知道答案,我要回答