Sebastian
Sebastian

Reputation: 141

Python 2.7 - how to count lines in files and use the results further

I have to write a script that lists all the text files in a directory, then counts the number of lines in each file and then gives you the max amount, the minimum amount and average.

so far I have this:

import glob
import os

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f, start = 1):
            pass
    return i

files = glob.glob("/home/seb/Learning/*.txt")
print files

length = []

for file in files:
    file_len(file)
    length.append(i)

print length

As you (and me) could expect it works up until

length.append(i)

because i is not identified - I thought it was worth a shot though.

My question would be, how can I use the return of the function to append it to a list?

Upvotes: 1

Views: 513

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124748

You need to assign the return value of file_len(file) to a variable:

flength = file_len(file)
length.append(flength)

The name i is a local name in file_len and not visible outside of the function, but the function does return the value.

Upvotes: 1

Related Questions