Python:将多行用户输入写入文本文件

标签 python python-3.x

我到底怎么才能做到这一点...我是 Python 新手,我正在尝试创建一个菜谱目录程序来存储我所有的菜谱...

我的代码的“添加菜谱”部分:

def add_recipe():
    recipe_name = input ("Recipe name: ");
    print('Please add the directions AND ingredients')
    with open (recipe_name + ".txt", "x") as f:
        f.write(input ());

我只需要多行用户输入...

编辑:我需要它进入 .txt 文件

最佳答案

您可以使用 iter(input, '') 接受输入,直到出现空行:

recipe_name = input ("Recipe name: ");
print('Please add the directions AND ingredients')
with open (recipe_name + ".txt", "x") as f:
    for line in iter(input, ''):
        f.write(line + '\n');

关于Python:将多行用户输入写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031215/

相关文章:

regex - Python : Count items, 将计数存储为变量,用于将字符串替换为外部文件中的项目数的语句

python - 当前冲刺编号的用户故事

python-3.x - map 绘图网格问题

python - 使用 docker-compose up 运行时如何优雅地停止 Dockerized Python ROS2 节点?

python - 使用 Python 正则表达式切入模式

python-3.x - 如何从不断刷新网页元素的网页中循环元素

python - 将键,值动态添加到python中的字典

python - 如何使用 Python 将 MongoDB 的 bsondump 转换为 JSON?

python - 如何使类方法返回其自身的新实例?

python - 使用 python-requests 获取文件大小,同时只获取标题