Python 编程 - 输入/输出

标签 python file text

我是 Python 新手,需要一些关于我的程序的帮助。我的问题还没有得到解答,感谢所有帮助我的人!

最佳答案

我建议您使用 python 标准库中的现成工具之一来为您完成这项工作,而不是尝试自己解析文本文件。有几种不同的可能性,包括 configparser , csv ,和 shelve 。但对于我的示例,我将使用 json .

json 模块允许您将 python 对象保存到文本文件中。由于您想按名称搜索食谱,因此最好创建一个食谱字典,然后将其保存到文件中。

每个菜谱也将是一个字典,并将按名称存储在菜谱数据库中。因此,首先,您的 input_func 需要返回一个食谱字典,如下所示:

def input_func(): #defines the input_function function
    ...
    return {
        'name': name,
        'people': people,
        'ingredients': ingredients,
        'quantity': quantity,
        'units': units,
        'num_ing': num_ing,
        }

现在我们需要几个简单的函数来打开和保存食谱数据库:

def open_recipes(path):
    try:
        with open(path) as stream:
            return json.loads(stream.read())
    except FileNotFoundError:
        # start a new database
        return {}

def save_recipes(path, recipes):
    with open(path, 'w') as stream:
        stream.write(json.dumps(recipes, indent=2))

就是这样!我们现在可以将其全部投入使用:

# open the recipe database
recipes = open_recipes('recipes.json')

# start a new recipe
recipe = input_func()

name = recipe['name']

# check if the recipe already exists
if name not in recipes:
    # store the recipe in the database
    recipes[name] = recipe
    # save the database
    save_recipes('recipes.json', recipes)
else:
    print('ERROR: recipe already exists:', name)
    # rename recipe...

...

# find an existing recipe 
search_name = str(input("What is the name of the recipe you wish to retrieve?"))

if search_name in recipes:
    # fetch the recipe from the database
    recipe = recipes[search_name]
    # display the recipe...
else:
    print('ERROR: could not find recipe:', search_name)

我显然留下了一些重要的功能供您解决(例如如何显示菜谱、如何重命名/编辑菜谱等)。

关于Python 编程 - 输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22769517/

相关文章:

python - 如何拆分列表元素并根据空格分隔符替换它们?

python - 从一个大字符串中提取参数值

ios - 我如何在 iOS 上使用 CoreGraphics 渲染的 pdf 上反转文本颜色?

python - 具有不规则采样率的傅里叶变换

python - Anaconda 未能通过 md5 检查更新?

python - 在 matplotlib 中找到图像上点击点的位置

linux - 复制文件保留文件夹结构

java - 创建新文件 - 获取 IOException

c++ - 具有 CREATE_ALWAYS 处置的 CreateFile 函数

android - 使文本完全适合屏幕大小