Python 写入文本文件错误

Python 写入文本文件错误,python,python-3.x,file-writing,Python,Python 3.x,File Writing,嗨,我正在编写一个程序,将一些文件存储到文本文档中,必要时可以重新加载。下面是代码的开头,但是当运行时,我收到一个回溯错误,指出“recipe\u title未定义”,当时我认为我已经将它定义为文本文件的名称。请帮我看看我做错了什么 import sys opt=0 def choice1(): print("WORKED") def choice2(): Recipe_Name = input("Please enter a recipe name: ") Reci

嗨,我正在编写一个程序,将一些文件存储到文本文档中,必要时可以重新加载。下面是代码的开头,但是当运行时,我收到一个回溯错误,指出“recipe\u title未定义”,当时我认为我已经将它定义为文本文件的名称。请帮我看看我做错了什么

import sys

opt=0

def choice1():
    print("WORKED")
def choice2():
    Recipe_Name = input("Please enter a recipe name: ")
    Recipe_List = open(recipe_title.txt,"w")
    Recipe_List.write(recipe_title+"\n")

def ingredient_input_loop(recipe_title, ):
        Recipefile = open(recipe_title,"w")
        if(ingredient== "end" or "End" or "END" or "EnD" or "eNd" or "enD" or "ENd" or "eND"):
            Recipe.write(recipe_title)

recipe_title.txt是您的文件名,不是变量。因此,您应该添加引号

Recipe_List = open('recipe_title.txt',"w")
或者如果配方名称确实是一个变量:

Recipe_List = open('{}.txt'.format(recipe_title),"w") # now you can open brocolli.txt for example
关于代码的一般反馈:

  • 变量名不应包含大写字符。这应该只是 用于类名
  • 检查是否可以将“end”的所有组合写入
    if component.lower()=“end”:
另请参见