如何修复UnboundLocalError:在赋值之前引用的局部变量'file_lines'

时间:2015-11-09 23:22:46

标签: variables python-3.x variable-assignment local

所以这是我的函数,用于读取文件中的文本行。

这是从较大的程序中提取的,因此一些评论可能看起来不合适。无论如何我需要在许多其他函数中使用函数text和file_lines,但即使在将它们声明为全局之后,仍然会在赋值错误之前获取UnboundLocalError:局部变量'file_lines',我不知道该怎么做。

import sys
text = []
case = ''
file_lines = []
def read_file(file):        # function to read a file and split it into lines
    global text             #sets variable text as a global variable for use in multiple locations
    global case             #handles case sensitivity.
try:                    #tests the statement after colon
    open(file) 
except:
    print('oops no file found bearing that name')      
else:                  
    while file == '':   #if the file name is blank print error, this prevents program from crashing
        print ('error')
        filename = input('enter a file and its extension ie file.ext\n>>')
    with open(file) as f :      #opens filewith name 

        text = f.read() #read all lines of program text.
        print ("file successfully read")
        print('TEXT SENSITIVITY TURNED ON !!!!!!')
        text = text.split('\n')# breaks lines in file into list  instead of using ".readlines"
                               # so that the program doesn't count blank lines 
        case == True

    global file_lines
    file_lines = text

尝试使用read_lines变量的函数将是

def find_words(words):        
    line_num = 0    # to count the line number
    number_of_word = 0
    if case == False:
        words = words.lower()
        file_lines = [file_lines.lower() for file_lines in text]
    while "" in file_lines:
            file_lines.remove('')      
    for lines in file_lines:

        line_num += 1
        if words in lines:  #checks each for the words being looks for
           print(line_num,"...", text[line_num-1])
           number_of_word = 1
    if number_of_word == 0: #to check if the word is located in the file
        print('Words not found')

1 个答案:

答案 0 :(得分:0)

在您的函数find_words中,您忘记指定find_lines是全局的。尝试

def find_words(words):
   global file_lines
   line_num = 0    # to count the line number

函数错误,因为file_lines未在find_words的范围内定义。