Carl Carl - 7 months ago 11
Python Question

How do I count the number of lines in a text file?

For python I have an assignment where I have to calculate the number of words in the text file and display the average number of words per sentence. However the average number of words turns up on always becoming one.

The text file is

Hello
How are you
I am fine
Have a good day
Bye


Here is the code

def main():
num_words = 0
total_words = 0
total_lines = 0

in_file = open("text.txt", "r")

line = in_file.readline()

while line != "":
num_words = 0
num_lines = 0
line_list = line.split()

for word in line_list:
num_words = num_words + 1

for line in line_list:
num_lines = num_lines + 1

total_words = total_words + num_words

total_lines = total_lines + num_lines
average = total_words / total_lines
line = in_file.readline()

print "Total words: ", total_words
print "Average number of words per sentence: ", average

in_file.close()

main()

Answer

A much better way to do this would be the following:

f = open('in_file.dat')

num_lines = 0
tot_words = 0

for line in f:
    num_lines += 1
    tot_words += len(line.split())

average = tot_words / num_lines

print(average)