Sunday, May 3, 2009

Add newline at the end of files

A simple Python script to automatically append newlines at the end of files, to make some compilers (especially some gcc versions) happy. It recursively looks for all files with extensions .cpp or .h and appends a newline if necessary.

#!/usr/bin/env python

import os, glob

# file extensions to search for
extensions = ('.cpp', '.h')

def process_file(filename):
    f = open(filename, 'r')
    last_line = f.readlines()[-1]
    f.close()
    # check if we need to append a newline
    if len(last_line.strip()) > 0:
        f = open(filename, 'a')
        print >> f, '\n'
        f.close()

def process_dir(dirname):
    for f in glob.glob('%s/*' % dirname):
        if os.path.isdir(f): # recurse
            process_dir(f)
        elif f.endswith(extensions):
            process_file(f)

if __name__ == '__main__':
    process_dir('.')