Tuesday, July 26, 2011

Python: Getting Line Counts of Files and Reading Directories

I have a bunch of little scripts to help out with day-to-day tasks (don't we all?). For some reason, (probably because I've been busy) I never posted anything tagged with "python". Whoa! Sharing is caring, so here it is.


import sys
import os

def lines_in_file(f):
    return len(open(f).readlines())

files = os.listdir(sys.argv[1])
totalcount = 0
for f in files:
    totalcount += lines_in_file(sys.argv[1] + f)

print totalcount

Why would this be helpful?

Well, it may or may not to you, but maybe you're just looking for a python example on how to get a line count of a file:
def lines_in_file(f):
    return len(open(f).readlines())

Or maybe, you're just looking for a python example to list files in a directory:
files = os.listdir(sys.argv[1])
for f in files:
    print f ## modified from the original script, to show you an example

How I Use It In Case You Were Curious...

So, we have this one cron job that parses through a directory that contains CSV files. So essentially, each line is a python run. Or I can also think of it as, X number of accounts are participating in Job Y.

That's it! Cheers!

No comments: