1

I have a text file with some records having similar fields.

    name:
    Class:
    Subject:
    name:
    Class:
    Subject:

As above mentioned this file can have any number of records and I want to separate each record with respective fields. Following is how far I could reach in order to pursue this problem.

    def counter(file_path):
       count = 0
       file_to_read = open(file_path)
       text_to_read = file_to_read.readlines()
       file_to_read.close()
       for line in text_to_read:
           if line.find('name') != -1:
              count = count + 1
       return count

This way i can count the no. of records present in the file and now I'm finding it difficult to split the whole text file in segments equal to no. of records.

Thanks in advance

4

1 に答える 1

3
def records(file_path):
    with open(file_path) as f:
        chunk = []
        for line in f:
            if 'name' in line:
                if chunk:
                    yield chunk
                chunk = [line]
            else:
                chunk.append(line)
        if chunk:
            yield chunk

for record in records('data.txt'):
    print '--------'
    print ''.join(record)

版画

--------
    name:
    Class:
    Subject:

--------
    name:
    Class:
    Subject:
于 2012-11-29T09:20:45.500 に答える