在另一个用户定义的函数中调用用户定义的函数时的Nameerror

时间:2015-11-25 23:19:25

标签: python

我需要编写一个程序来打开和读取文件,并包含单独的用户定义函数,用于计算文件中的行数和单词数,例如linecount(),wordcount()等。我起草了下面的代码,但我不断收到一个名称错误,上面写着"全球名称' f'未定义"。 f是应该由openfile()函数返回的文件句柄。有什么建议吗?

#open and read file
def openfile():
    import string
    name = raw_input ("enter file name: ")
    f = open (name)

# Calculates the number of paragraphs within the file 
def linecount():
    openfile()
    lines = 0
    for line in f:
        lines = lines + 1
    return lines

#call function that counts lines
linecount()

1 个答案:

答案 0 :(得分:2)

因为f是openfile中的局部变量

def openfile():
    import string
    name = raw_input ("enter file name: ")
    return open (name)

# Calculates the number of paragraphs within the file 
def linecount():
    f = openfile()
    lines = 0
    for line in f:
        lines = lines + 1
    return lines

甚至更短

def file_line_count():
    file_name = raw_input("enter file name: ")
    with open(file_name, 'r') as f:
        return sum(1 for line in f)