iterating through files

Mensanator mensanator at aol.com
Thu Feb 19 18:05:22 EST 2009


On Feb 19, 4:56 pm, Steve Holden <st... at holdenweb.com> wrote:
> Chris Rebert wrote:
> > On Thu, Feb 19, 2009 at 2:28 PM, Mike Driscoll <kyoso... at gmail.com> wrote:
> >> On Feb 19, 4:22 pm, Mike Driscoll <kyoso... at gmail.com> wrote:
> >>> On Feb 19, 3:56 pm, oamram <oam... at gmail.com> wrote:
>
> >>>> Hi Pythonist,
> >>>> new to python. i have a directory with about 50 text file and i need to
> >>>> iterate through them and get
> >>>> line 7 to 11 from each file and write those lines into another file(one file
> >>>> that will contain all lines).
> >>>> Cheers, Omer.
> >>>> --
> >>>> View this message in context:http://www.nabble.com/iterating-through-files-tp22048070p22048070.html
> >>>> Sent from the Python - python-list mailing list archive at Nabble.com.
> >>> I would recommend using the glob module to grab a list of the files
> >>> you want or you can just create your own list. Then use a loop to grab
> >>> the lines you want. Something like this:
>
> >>> f = open(textFile)
> >>> newFile = open(newFileName, "a")
> >>> x = 1
> >>> for line in f.readlines():
> >>>     if x >=7 and x <=11:
> >>>          newFile.write(line + "\n")
>
> >>> You could even put the above inside a loop that loops over the list of
> >>> files. Anyway, that's one approach. I'm sure there are many others.
>
> >>> Mike
> >> Oops...I forgot to iterate the counter. The code should look like
> >> this:
>
> >> <code>
>
> >> f = open(textFile)
> >> newFile = open(newFileName, "a")
> >> x = 1
> >> for line in f.readlines():
> >>    if x >=7 and x <=11:
> >>         newFile.write(line + "\n")
> >>    x +=1
>
> >> </code>
>
> > Or you could use enumerate(); also, readlines() isn't necessary:
>
> > f = open(textFile)
> > newFile = open(newFileName, "a")
> > for x, line in enumerate(f):
> >     if x >=7 and x <=11:
> >         newFile.write(line + "\n")
>
> > Sounds a bit like homework to me though...
>
> But all these solutions read the whole file.  You should really read six
> lines throwing them away then read five lines to keep.

It might be useful not to assume every file has at least 11 lines
and program accordingly.

>
> Since this might be homework I'll not write the code, but it will
> involve f.next() ...
>
> regards
>   Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/- Hide quoted text -
>
> - Show quoted text -




More information about the Python-list mailing list