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" : 2}
file = open("Python.txt", "w")
file.write("%s = %s" %("dict1", dict1))
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)
3、使用 pickle 模块将变量保存在文件中
以下示例,使用 “wb” 模式打开文件。使用 pickle.dump() 将变量以 ASCII 格式写入文件。import pickle
dict1 = {"one" : 1, "two" : 2}
file = open("Python.txt", "wb")
pickle.dump(dict1,file)
file.close()
with open('Python.txt', 'rb') as f:
d = pickle.load(f)
print(d)4、使用 numpy 模块将变量保存在文件中
在此示例中,我们使用 numpy 模块的 savetxt() 函数将列表存入文本文件。import numpy as np
list1 = [1,2,3]
np.savetxt('Python.txt',list1)
#读取
# 使用 np.loadtxt() 读取保存的数据
loaded_data = np.loadtxt('Python.txt')
# 输出读取到的数据
print(loaded_data)
网友回复
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?
linux上如何运行任意windows程序?
ai能写出比黑客还厉害的零日漏洞等攻击工具攻击任意软件系统工程?
js如何获取浏览器的音频上下文指纹、Canvas指纹、WebGL渲染特征?
为啥ai开始抛弃markdown文本,重新偏好html文本了?
网站有没有办法鉴别访问请求是由ai操控chrome-devtools-mcp发出的?


