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?