Python 写入文件问题和显示文件内容
我目前在为文件编写字典后,无法正确显示该文件。对于该程序,输入文件需要具有以下格式: ID:Date:Dayskept:ProductName例如1:12/12/2011:12:A 在我第一次将示例文件读入词典时,这很好,但在我将词典保存到新文件并尝试打开此文件后,我会得到以下输出: 1:“日期”:2011年12月12日,“生活”:12,“姓名”:A 在将数据写入文件之前,是否有一种简单的方法来格式化字典中的数据? 谢谢你的建议Python 写入文件问题和显示文件内容,python,dictionary,file-handling,Python,Dictionary,File Handling,我目前在为文件编写字典后,无法正确显示该文件。对于该程序,输入文件需要具有以下格式: ID:Date:Dayskept:ProductName例如1:12/12/2011:12:A 在我第一次将示例文件读入词典时,这很好,但在我将词典保存到新文件并尝试打开此文件后,我会得到以下输出: 1:“日期”:2011年12月12日,“生活”:12,“姓名”:A 在将数据写入文件之前,是否有一种简单的方法来格式化字典中的数据? 谢谢你的建议 def loadProduct(fileName):
def loadProduct(fileName):
global cheeseDictionary
f = open(fileName,"r")
line = f.readline() # Reads line from file
while line:
line = line[:-1]
data = split(line,":") # Splits line when there is a colon
cheeseDictionary[data[0]] = {"date":data[1], "life":data[2], "name":data[3]} # Stores each split item
line = f.readline() # Next line
f.close()
print cheeseDictionary
def saveProduct(fileName):
global cheeseDictionary
f = open(fileName,"w")
pickle.dump(cheeseDictionary, f)
f.close()
因为您有一个特定的格式,所以需要编写代码来发出该格式。(我不知道你想用
pickle
做什么,它生成的二进制格式与你所说的没有任何相似之处。)
例如,您可以像这样重新定义saveProduct
:
def saveProduct(fileName, cheeseDictionary):
f = open(fileName, "w")
for i in sorted(cheeseDictionary.keys()):
v = cheeseDictionary[i]
f.write("%s:%s:%s:%s\n" % (i, v["date"], v["life"], v["name"]))
作为旁注,
global cheasteddictionary
行是完全不必要的,当我尝试使用该方法写入文件时,一定忘了删除pickle。非常感谢您的帮助代码现在运行良好:)