spookyblack spookyblack - 1 year ago 98
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!)

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download