Python有几种方法可以将字典写入文件:
data = {"key1": "value1", "key2": "value2"}
with open("output.txt", "w") as file:
for key, value in data.items():
file.write(f"{key}: {value}\n")
import json
data = {"key1": "value1", "key2": "value2"}
with open("output.json", "w") as file:
json.dump(data, file)
import pickle
data = {"key1": "value1", "key2": "value2"}
with open("output.pickle", "wb") as file:
pickle.dump(data, file)
这些方法可以根据需要选择适合的方式将字典写入文件。