Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92568

Re: Path, strings, and lines

References <56ac4185-3d58-473a-ad40-99d9366a8bb3@googlegroups.com>
Date 2015-06-13 09:47 +1000
Subject Re: Path, strings, and lines
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.448.1434152856.13271.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Jun 13, 2015 at 5:39 AM, Malik Rumi <malik.a.rumi@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Path, strings, and lines Malik Rumi <malik.a.rumi@gmail.com> - 2015-06-12 12:39 -0700
  Re: Path, strings, and lines Ian Kelly <ian.g.kelly@gmail.com> - 2015-06-12 14:30 -0600
    Re: Path, strings, and lines Malik Rumi <malik.a.rumi@gmail.com> - 2015-06-12 21:48 -0700
      Re: Path, strings, and lines MRAB <python@mrabarnett.plus.com> - 2015-06-13 19:25 +0100
        Struggling with os.path.join and fileinput (was 'Path, strings, and lines' Malik Rumi <malik.a.rumi@gmail.com> - 2015-06-15 19:00 -0700
          Re: Struggling with os.path.join and fileinput (was 'Path, strings, and lines' Ian Kelly <ian.g.kelly@gmail.com> - 2015-06-15 20:44 -0600
          Re: Struggling with os.path.join and fileinput (was 'Path, strings, and lines' MRAB <python@mrabarnett.plus.com> - 2015-06-16 03:51 +0100
  Re: Path, strings, and lines Chris Angelico <rosuav@gmail.com> - 2015-06-13 09:47 +1000
    Re: Path, strings, and lines Malik Rumi <malik.a.rumi@gmail.com> - 2015-06-12 21:50 -0700

csiph-web