1

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 e.g. linecount(), wordcount()etc. I drafted the below code, but I keep getting a name error that says "global name 'f' is not defined". f is a file handle that should be returned by the openfile() function. 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()

1 Answer 1

2

Because f is local variable in 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)
Sign up to request clarification or add additional context in comments.

1 Comment

@ kAlmAcetA: Many thanks for your response and solution. Does the trick!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.