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.

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)

Need Your Help

Get only properties that implement an interface

c# reflection

I have an class that implements an interface. I'd like to examine only the property values that implement my interface.

Debugging menu disabled in NetBeans 7.3

php netbeans xdebug remote-debugging

I have for long used NetBeans and Xdebug successfully to debug my PHP code running on a remote test server. However, after upgrading to NetBeans 7.3, the Debug menu is almost entirely disabled and I

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.