打开文本文件时,我正在努力访问使用.readlines()创建的列表。该文件打开正确,但我不知道如何访问函数'display_clues()'中的列表。
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clues_open()
print(clue_list)
错误:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
display_clues()
File "N:\Personal Projecs\game\game.py", line 35, in display_clues
print(clue_list)
NameError: name 'clue_list' is not defined
谢谢!
答案 0 :(得分:1)
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
#print clue_list #either print the list here
return clue_list # or return the list
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = raw_input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clue_list = clues_open() # catch list here
print clue_list
display_clues()
答案 1 :(得分:0)
您必须将列表从clues_open()
返回到display_clues()
:
def clues_open():
with open("clues.txt","r") as cluesfile:
return cluesfile.readlines()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
if clues_yes_or_no.lower() == "y":
clues_list = clues_open()
print(clue_list)
作为旁注:除了阻止之外,我删除了你的无用而无用的东西。永远不要使用裸的except子句,永远不要假设实际出错的地方,只捕获你可以真正处理的异常。