This is a slightly modified version of Lattywares solution. Since it is not possible to append data to the beginning of a file, the whole content is read and the file is written anew including your header. By opening the file in read/write mode we can do both operations with the same file handler without releasing it. This should provide some protection against race conditions.
try: with open(filename, 'r+') as f: data = f.read() f.seek(0,0) f.write(header) f.write(data) #f.truncate() is not needed here as the file will always grow print("Header added to", filename)except IOError: print("Sorry, could not open file for reading/writing")