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)
這些方法可以根據需要選擇適合的方式將字典寫入文件。