Python Ensure File ends in line return?
I would like to have a function which takes in a path to a file, checks if the file ends in an \n, and add in a \n if it doesn't.
I know that I could do this by opening the file twice, once in read mode and then again in append mode, but I feel like I must be missing something... I feel like 'w+' mode, for example, must be able to do it.
Here's a way of doing this opening the file twice (I want something simpler where you only open it once).
def ensureFileEndsWith(path, end): with open(path) as f: f.seek(-1, 2) alreadyGood = f.read(1) == end if not alreadyGood: with open(path, 'a') as f: f.write(end)
I want to do the same thing, but only opening the file once. I tried this:
def ensureFileEndsWith(path, end): with open(path, 'w+') as f: f.seek(-1, 2) if not f.read(1) == end: f.write(end)
But it printed out this exception:
IOError: [Errno 22] Invalid argument
Regarding my usage of seek in a file opened in 'w+' mode.
First of all you want open(path, 'r+'); 'w+' truncates the file. The reason you were getting that error is because you can't do f.seek(-1, 2) into an empty file. This should do it for you:
def ensureFileEndsWith(path, end): with open(path, 'r+') as f: try: f.seek(-len(end), 2) except IOError: # The file is shorter than end (possibly empty) f.seek(0, 2) # Passing in a number to f.read() is unnecessary if f.read() != end: f.write(end)