[英]Nameerror when calling a user-defined function in another user-defined function
I need to write a program that opens and reads a file and contains separate user-defined functions for counting the number of lines and words in the file eg linecount(), wordcount()etc. 我需要编写一个程序来打开和读取文件,并包含单独的用户定义函数来计算文件中的行数和单词数,例如linecount(),wordcount()等。 I drafted the below code, but I keep getting a name error that says "global name 'f' is not defined".
我起草了以下代码,但始终收到名称错误,提示“未定义全局名称'f'”。 f is a file handle that should be returned by the openfile() function.
f是应由openfile()函数返回的文件句柄。 Any advise?
有什么建议吗?
#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()
Because f
is local variable in openfile 因为
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
or even shorter 甚至更短
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.