spookyblack spookyblack - 4 months ago 10x
Python Question

Finding average length per line in a file using Python

I'm very beginner at Python. My question is as the title states, how would I write a function that would return the average line length in a file? (Not really sure how to incorporate files in functions) (Any help would help!)


Pretty straightforward, sum the length of the lines then divide by the number of lines.

with open("testfile.txt", "r") as f:
    lines = f.readlines()
    print(sum(len(line) for line in lines) / len(lines))