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]
    # check if we need to append a newline
    if len(last_line.strip()) > 0:
        f = open(filename, 'a')
        print >> f, '\n'

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

if __name__ == '__main__':