该怎么做...我是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文件
答案 0 :(得分:2)
您可以使用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');
答案 1 :(得分:1)
在readlines()
上尝试sys.stdin
:
>>> import sys
>>> sys.stdin.readlines()
first line
second line
third line
<Ctrl+D>
['first line\n', 'second line\n', 'third line\n']
答案 2 :(得分:0)
使用while循环,或继续附加到列表:
l=[]
a=input()
while a:
l.append(a)
a=input()
print(l)
示例输出:
First line
Second line
['First line', 'Second line']
或输入完整代码:
reciept_name=input('Reciept: ')
a=input('Your input: ')
with open(reciept_name+'.txt','w') as f:
while a:
f.write(a+'\n')
a=input('Your input: ')
示例输出:
Reciept: Bob
Your input: 123
Your input: 456
Your input: abc
Your input: