Avoid newline at the end

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Nov 11 06:59:02 EST 2007


On Sun, 11 Nov 2007 11:22:19 +0100, Florian Lindner wrote:

> Hello,
> I have a piece of code like that:
> 
>     for row in resultSet:
>         logs += "/home/%s/%s/log/access.log \n" % (row[1], row[0]) 
>         logs += "/home/%s/%s/log/error.log \n" % (row[1], row[0]) # <--
> 
> Now I want to avoid the newline at the last iteration and only at the
> second line.

That means your log file doesn't end with a newline. That's often not 
good, because it can confuse some tools.

Also, appending lots of strings together like that is very inefficient. 

> How to do that most elegantly with Python?

If you have a small number of rows (say, less than a few tens of 
thousands), you can do this:

rows = []
for row in resultSet:
    rows.append("/home/%s/%s/log/access.log" % (row[1], row[0]))
    rows.append("/home/%s/%s/log/error.log" % (row[1], row[0]))
    # note that there are no newlines
logs = '\n'.join(rows) # do it once at the end

But again, when you write text to a file, you should end it with a 
newline. It isn't compulsory, but it is best practice.

Alternatively, check out the logging module.



-- 
Steven.



More information about the Python-list mailing list