我试图编写一些代码来创建一个文件来写一个关于"字符的数据"。我已经能够使用以下方式编写字符串:
f = open('player.txt','w')
f.write("Karatepig")
f.close()
f = open('player.txt','r')
f.read()
问题是,如何将除字符串以外的内容存储到文件中?我可以将它从字符串转换为值吗?
答案 0 :(得分:3)
文件只能存储字符串,因此您必须在编写时将其他值转换为字符串,并在阅读时将它们转换回原始值。
Python标准库有whole section dedicated to data persistence,可以帮助您轻松完成此任务。
但是,对于简单类型,最简单的方法是使用json
module将数据序列化到文件并轻松地再读回来:
import json
def write_data(data, filename):
with open(filename, 'w') as outfh:
json.dump(data, outfh)
def read_data(filename):
with open(filename, 'r') as infh:
json.load(infh)