Katie Greene
Katie Greene

Reputation: 21

How to call multiple functions using a file in python

I have multiple functions that I have to run. Both functions that I have run individually just fine, however when I try to run them simultaneously, only the first function runs correctly.

#Read file Emma.txt
fin = open('Emma.txt', 'r')


'''
Write a function wordNumbers which takes the file name and return
number of words in the file
'''

def wordNumbers(fin):

    #count the number of words.
    num_words = 0  #staring point for line
    for line in fin:
            words = line.split() #create a list of line
            num_words += len(words) #add each line legnth together
    print num_words #print total number of words

def lineNumbers(fin):

    #count the number of lines with a counter and while loop
    cnt = 0
    for line in fin:
            if cnt < line:
                    cnt += 1
    print cnt

wordNumbers(fin)

lineNumbers(fin)

Upvotes: 2

Views: 2209

Answers (3)

shahram kalantari
shahram kalantari

Reputation: 863

The problem is when you open a file and start reading from it, your position on file does not get reset until you close it. fin = open('Emma.txt', 'r') opens the file and then you use two functions to read from the file, while you should close it (or seek to the beginning using fin.seek(0)) after the first function call and open it again so that you read the file from the beginning again.

Upvotes: 1

furas
furas

Reputation: 142879

You have to move to the beginning of file

wordNumbers(fin)
fin.seek(0) #  move to the beginning
lineNumbers(fin)

or reopen file

fin = open('Emma.txt', 'r')
wordNumbers(fin)
fin.close()

fin = open('Emma.txt', 'r')
lineNumbers(fin)
fin.close()

Upvotes: 2

Tom Karzes
Tom Karzes

Reputation: 24062

After the first call, you've exhausted the input. In order to do what you want, you need to seek back to the beginning before the second call. Just add a seek call between the two as follows:

wordNumbers(fin)
fin.seek(0)
lineNumbers(fin)

Upvotes: 1

Related Questions