Avoid newline at the end

Florian Lindner Florian.Lindner at xgm.de
Sun Nov 11 13:18:25 EST 2007


Steven D'Aprano wrote:

> 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.

That is not log file it's a config file for logrotate. And the log string
goes into a template therefore the config file ends with a newline. The
problem is that logrotate gets confused by empty lines between logfile path
and config.
The number of lines will always be < 100 and so config will only be
regenerated not often so efficiency is not issue.


Regards,

Florian



More information about the Python-list mailing list