簡體   English   中英

使用.readlines()並努力訪問列表

[英]Using .readlines() and struggling to access the list

打開文本文件時,我正在努力訪問使用.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

謝謝!

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

您必須將列表從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子句,永遠不要假設實際出了什么問題,只捕獲真正可以處理的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM