1

I'm trying to print the number of lines in a file, when I use the code outside of a function, it works fine:

input_file_name = input("Please Enter the name of your text file: ")
infile = open(input_file_name, "r")

listOfLines = infile.readlines()
count = 0
char = " "

for line in listOfLines :
    text = line.rstrip()
    while char != "":
        char = infile.read(1)
    count = count + 1
print(count)


infile.close()

but when I use the same code inside of a function it prints a value of 0 instead of 5 (which is the length of my test file).

def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r")
    print()

    print_file(infile)
    count_lines(infile)

    infile.close()


def print_file(infile):
    listOfLines = infile.readlines()
    for line in listOfLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    listOfLines = infile.readlines()
    count = 0
    char = " "

    for line in listOfLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print(count)

main()

However, if I remove the function

def print_file(infile):
listOfLines = infile.readlines()
for line in listOfLines:
    text = line.rstrip()
    print(text)

and the call for the function,

print_file(infile)

it works fine. Why does the first function effect how the second function prints?

C.StG
  • 69
  • 9
  • Because `print_file` consumes the file and you don't reset the stream back to the beginning. – MFisherKDX Nov 13 '17 at 03:15
  • Because the first function leaves the file at the EOF. So the next function has nothing to read. Try adding `infile.seek(0)` at the start of your count_lines() method to reset the file to its start. – John Anderson Nov 13 '17 at 03:15
  • 1
    Possible duplicate of [Why can't I call read() twice on an open file?](https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file) – MFisherKDX Nov 13 '17 at 03:19

1 Answers1

2

The file object you create using infile = open(input_file_name, "r") is an iterator. It can be looped over one time only.

Your print_file function performs the first iteration over the file, exhausting its content. When you attempt the second iteration in count_lines, the iterator has ended, so nothing else occurs.

James
  • 32,991
  • 4
  • 47
  • 70