写入文本文件错误

时间:2015-03-17 14:22:00

标签: python python-3.x file-writing

您好我正在制作一个程序,将一些文件存储到文本文档中,必要时可以重新加载。下面是代码的开头,但是当运行时,我收到一个跟踪错误,指出“recipe_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)

1 个答案:

答案 0 :(得分:1)

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

Recipe_List = open('recipe_title.txt',"w")

或者如果recipe_title确实是一个变量:

Recipe_List = open('{}.txt'.format(recipe_title),"w") # now you can open brocolli.txt for example

有关您的代码的一般反馈:

  • 变量名称不应包含大写字符。这应该只 用于班级名称。
  • 检查'end'的所有组合是否可以写入if ingredient.lower() == "end":
相关问题