使用.readlines()并努力访问lis

2024-07-01 07:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

打开文本文件时,我很难访问使用.readlines()创建的列表。文件打开正确,但我不确定如何访问函数“display\u 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

谢谢!你知道吗


Tags: orno列表defdisplaylineopenlist
2条回答

必须将列表从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子句,永远不要假设实际发生了什么错误,只有catch异常您才能真正处理。你知道吗

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

相关问题 更多 >

    热门问题