Path, strings, and lines

Chris Angelico rosuav at gmail.com
Fri Jun 12 19:47:28 EDT 2015


On Sat, Jun 13, 2015 at 5:39 AM, Malik Rumi <malik.a.rumi at gmail.com> wrote:
> for line in lines:
>      for item in fileinput.input(s2):
>          if line in item:
>             with open(line + '_list', 'a+') as l:
>                 l.append(filename(), filelineno(), line)

Ian's already answered your actual question, but I'll make one
separate comment. What you have here will open, append to, and close,
the list file for every single line that you find. If you're expecting
to find zero or very few lines, then that's fine, but if you expect
you might find a lot, this will be extremely slow. Much more efficient
would be to open the file once, and write to it every time - just
switch around the nesting a bit:

with open(line + '_list', 'a+') as l:
     for line in lines:
         for item in fileinput.input(s2):
             if line in item:
                l.append(filename(), filelineno(), line)

(Although you may want to rename your open file object, here; "l"
isn't a very useful name at the best of times, so I'd be inclined to
call it "log".)

ChrisA



More information about the Python-list mailing list