简体   繁体   中英

Using .readlines() and struggling to access the list

I am struggling to access the list created by using .readlines() when opening the text file. The file opens correctly, but I am not sure how I can access the list in the function '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)

Error:

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

Thanks!

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()

You have to return the list from clues_open() to 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) 

As a side note: I removed your worse than useless except block. Never use a bare except clause, never assume what actually went wrong, and only catch exception you can really handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM