Text processing and file creation

Arnau Sanchez arnau at ehas.org
Thu Sep 6 07:47:05 EDT 2007


malibuster at gmail.com escribió:

> I am still wondering how to do this efficiently in Python (being kind
> of new to it... and it's not for homework).

You should post some code anyway, it would be easier to give useful advice (it 
would also demonstrate that you put some effort on it).

Anyway, here is an option. Text-file objects are line-iterable, so you could use 
itertools (perhaps a bit difficult module for a newbie...):

from itertools import islice, takewhile, repeat

def take(it, n):
     return list(islice(it, n))

def readnlines(fd, n):
     return takewhile(bool, (take(fd, n) for _ in repeat(None)))

def splitfile(path, prefix, nlines, suffix_digits):
     sformat = "%%0%dd" % suffix_digits
     for index, lines in enumerate(readnlines(file(path), nlines)):
         open("%s_%s"%(prefix, sformat % index), "w").writelines(lines)

splitfile("/etc/services", "out", 5, 4)

arnau



More information about the Python-list mailing list