用Python编写和读取列表到文本文件:有没有更有效的方法? [英] Writing and reading lists to text files in Python: Is there a more efficient way?
问题描述
下面是一个程序,要求用户输入食谱并将其配料存储在一组列表中.然后,程序将列表数据存储到文本文件中.如果选择了选项2,它将从文本文件中检索存储的数据,并将其加载回程序中进行处理,并显示给用户.
Below is a program which asks the user to enter a recipe and stores their ingredients in a set of lists. The program then stores the list data into a text file. If option 2 is chosen it will retrieve the stored data from the text file and load it back into the program for processing and to be displayed to the user.
文本文件不需要以人类可读的格式存储数据,但是在检索之后,文本文件必须采用可以识别每个列表项并且数量值需要能够进行计算的格式.
The text file doesn't need to store data in a human readable format but after retrieval it must be in a format where each list item can be identifiable and the quantities values need to be able to undergo a calculation.
我的方法是将列表轻松转储到文本文档中.检索数据时,它首先将每行添加到变量中,除去方括号,语音标记等,然后将其拆分回列表.
My method was to dump the lists into a text document easily. When retrieving the data it first adds each line to a variable, removes the square brackets, speech marks etc and then splits it back into a list.
这些似乎是一个漫长而漫长且效率低下的方式.当然,有一种更简单的方法可以将列表数据存储到文件中,然后直接检索回到列表中?
These seems to be a rather long winded and inefficient way of doing it. Surely there is an easier way to store list data into a file and then retrieve straight back into a list?
那么,有没有更简单,更有效的方法? 还是有另一种更简单/更有效的方法?
So, is there an easier more efficient way? Or, is there an alternative method which is again more simple / efficient?
while True:
print("1: Enter a Recipe")
print("2: Calculate Your Quantities")
option = input()
option = int(option)
if option == 1:
name = input("What is the name of your meal?: ")
numing = input("How many ingredients are there in this recipe?: ")
numing = int(numing)
orignumpep = input("How many people is this recipe for?: ")
ingredient=[]
quantity=[]
units=[]
for x in range (0,numing):
ingr = input("Type in your ingredient: ")
ingredient.append(ingr)
quant = input("Type in the quantity for this ingredient: ")
quantity.append(quant)
uni = input("Type in the units for this ingredient: ")
units.append(uni)
numing = str(numing)
ingredient = str(ingredient)
quantity = str(quantity)
units = str(units)
recipefile = open("Recipe.txt","w")
recipefile.write(name)
recipefile.write("\n")
recipefile.write(numing)
recipefile.write("\n")
recipefile.write(orignumpep)
recipefile.write("\n")
recipefile.write(ingredient)
recipefile.write("\n")
recipefile.write(quantity)
recipefile.write("\n")
recipefile.write(units)
recipefile.close()
elif option == 2:
recipefile = open("Recipe.txt")
lines = recipefile.readlines()
name = lines[0]
numing = lines[1]
numing = int(numing)
orignumpep = lines[2]
orignumpep = int(orignumpep)
ingredients = lines[3].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
quantitys = lines[4].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
unitss = lines[5].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
ingredient=[]
quantity=[]
units=[]
ingredient = ingredients.split()
quantity = quantitys.split()
units = unitss.split()
for x in range (0,numing):
quantity[x] = int(quantity[x])
numberpep = input("How many people is the meal for?")
numberpep = int(numberpep)
print("New Ingredients are as follows...")
for x in range (0,numing):
print(ingredient[x], " ", quantity[x]/orignumpep*numberpep, units[x])
input()
非常感谢!
推荐答案
您可以使用序列化格式; Python提供了几种.
You could use a serialisation format; Python offers several.
对于包含字符串信息的列表或字典,我将通过 json
模块,因为它是一种合理可读的格式:
For a list or dictionary containing string information, I'd use JSON, via the json
module, as it is a format reasonably readable:
import json
# writing
with open("Recipe.txt","w") as recipefile:
json.dump({
'name': name, 'numing': numing, 'orignumpep': orignumpep,
'ingredient': ingredient, 'quantity': quantity, 'units': units},
recipefile, sort_keys=True, indent=4, separators=(',', ': '))
# reading
with open("Recipe.txt") as recipefile:
recipedata = json.load(recipefile)
# optional, but your code requires it right now
name = recipedata['name']
numing = recipedata['numing']
orignumpep = recipedata['orignumpep']
ingredient = recipedata['ingredient']
quantity = recipedata['quantity']
units = recipedata['units']
json.dump()
配置将产生可读性强的数据,最重要的是,您不必将任何内容转换回整数或列表.都是为您保留的.
The json.dump()
configuration will produce very readable data, and most of all, you don't have to convert anything back to integers or lists; that is all preserved for you.
这篇关于用Python编写和读取列表到文本文件:有没有更有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!