写入文件问题并显示文件内容
当我将字典写入文件后,我目前无法正确显示文件。对于该程序,输入文件需要具有以下格式: ID: Date: Dayskept: ProductName 例如 1:12/12/2011:12:A
第一次将示例文件读入字典时这很好,但一旦我将字典保存到新文件并尝试打开此文件我得到输出: 1:"date":12/12/2011, "life":12, "name":A
有没有一种简单的方法可以在将字典中的数据写入文件之前对其进行格式化? 感谢您提供的任何建议
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()
I am currently having problems displaying a file correctly once i have written a dictionary to the file. For this program the input file needs to have the format:
ID: Date: Dayskept: ProductName e.g. 1:12/12/2011:12:A
This is fine the first time I read the example file into a dictionary, but once i save the dictionay into a new file and try to open this file i get the output:
1:"date":12/12/2011, "life":12, "name":A
Is there an easy way to format the data in the dictionary before it is written to file?
Thanks for any advice given
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您有所需的特定格式,因此您需要编写代码来发出该格式。 (我不知道你想用其中的
pickle
做什么,这会产生一种二进制格式,与你所说的没有任何相似之处。)例如,你可以像这样重新定义
saveProduct
:Since you have a specific format you want, you're going to need to write code to emit that format. (I don't know what you're trying to do with
pickle
in there, that produces a binary format that doesn't bear any resemblance to what you say you're getting.)For instance, you could redefine
saveProduct
like so: