使Python显示目录中的.txt文件

时间:2014-06-07 12:33:25

标签: python

print "Which category would you like to view? Savory, Dessert, Cake, Soup or Drink?    "
category = raw_input()
if category == "Savory": #opens directory according to their answer.
    os.listdir("savory")

elif category == "Drink":
    os.listdir("drink")

elif category == "Cake":
    os.listdir("cake")

elif category == "Dessert":
    os.listdir("dessert")

elif category == "savory":
    os.listdir("savory")

elif category == "drink":
    os.listdir("drink")

elif category == "cake":
    os.listdir("cake")

elif category == "dessert":
    os.listdir("dessert")

我正在尝试创建一个代码,用于显示已保存在某些目录下的食谱。当我运行代码时,即使我将配方输入目录,也不显示任何内容。

1 个答案:

答案 0 :(得分:3)

首先,您不打印任何内容。 E.g

os.listdir("savory")

应该是

print(os.listdir("savory"))

其次,您可以大大缩短代码:

print("Which category would you like to view? Savory, Dessert, Cake, Soup or Drink?")
print(os.listdir(raw_input().lower()))

如果您想限制用户访问其他目录:

safe = ['savory', 'dessert', 'cake', 'soup', 'drink']

category = raw_input().lower()
if category in safe:
    print(os.listdir(category))
else:
    print('You have typed an invalid category')