The correct course of action here is to try and read the file, if it works, read the data, then write to the file with the new data.
Writing to a file will create the file if it doesn't exist, and overwrite existing contents.
I'd also note you are using the with statement in an odd manner, consider:
try: with open(filename, 'w') as f: f.seek(0,0) f.write(header) print("Header added to", filename)except IOError: print("Sorry could not open file, please check path")
This way is more readable.
To see how to do this the best way possible, see user1313312's answer. My method works but isn't the best way, I'll leave it up for my explanation.
Old answer:
Now, to solve your problem, you really want to do something like this:
def add_header(filename): header = '"""\nName of Project"""' try: with open(filename, 'r') as f: data = f.read() with open(filename, 'w') as f: f.write(header+"\n"+data) print("Header added to"+filename) except IOError: print("Sorry could not open file, please check path")if __name__ == "__main__": filename = raw_input("Please provide path to file: ") add_header(filename)
As we only have the choices of writing to a file (overwriting the existing contents) and appending (at the end) we need to construct a way to prepend data. We can do this by reading the contents (which handily checks the file exists at the same time) and then writing the header followed by the contents (here I added a newline for readability).