在python中拆分文本文件 [英] Split the text file in python

查看:59
本文介绍了在python中拆分文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含一些具有相似字段的记录.

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

这样我就可以数数了.文件中存在的记录数,现在我发现很难将整个文本文件分成等于 no 的段.记录.

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.

提前致谢

推荐答案

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:

这篇关于在python中拆分文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆