Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Ensure File ends in line return?

Tags:

python

file

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.

like image 424
ArtOfWarfare Avatar asked Feb 11 '26 09:02

ArtOfWarfare


1 Answers

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)
like image 160
Cyphase Avatar answered Feb 13 '26 09:02

Cyphase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!