Python program to count lines in a .txt file

I am having some trouble with my code. I tried it out in my terminal window and it ran perfectly but every time i try to put it into my code editor an error keeps popping up in line 5. I am really not sure I am doing any of this right. Any help would be appreciated.Screenshot 2020-03-20 at 6.36.24 PM

Couldn´t you add a for statement before the “i in file” to create a loop.

Also remember to correctly indent your code.

Regards.

1 Like

Yes. Python requires indentation. The code needs to know what is inside the scope of the while loop. I also think that you likely need a for at the sort of line 5.

thank you for help. got it working!

1 Like
with open('test.py') as f:
    lines = f.readlines()
    line_count = len(lines)
    word_count = sum([len(line.split()) for line in lines])
    print('Total lines: {}'.format(line_count))
    print('Total words: {}'.format(word_count))