iterating through files

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Fri Feb 20 09:08:36 CET 2009


On Thu, 19 Feb 2009 13:56:38 -0800, oamram wrote:

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

Untested:

from __future__ import with_statement
from glob import glob
from itertools import islice


def main():
    with open('result.txt', 'w') as out_file:
        for filename in glob('foo/*.txt'):
            with open(filename, 'r') as lines:
                out_file.writelines(islice(lines, 7, 12))


if __name__ == "__main__":
    main()


Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list