如何在python中逐块读取文件

时间:2015-09-29 19:12:03

标签: python file python-2.7 file-read

我在按块读取文件时遇到困难,并且在每个块中获取一些选择性数据时遇到困难:

这是我的文件内容:

DATA.txt

#-----FILE-----STARTS-----HERE--#
#--COMMENTS CAN BE ADDED HERE--#

BLOCK IMPULSE DATE 01-JAN-2010 6 DEHDUESO203028DJE \
    SEQUENCE=ai=0:at=221:ae=3:lu=100:lo=NNU:ei=1021055:lr=1: \
    USERID=ID=291821 NO_USERS=3 GROUP=ONE id_info=1021055 \
    CREATION_DATE=27-JUNE-2013 SN=1021055  KEY ="22WS \
    DE34 43RE ED54 GT65 HY67 AQ12 ES23 54CD 87BG 98VC \
    4325 BG56"

BLOCK PASSION DATE 01-JAN-2010 6 DEHDUESO203028DJE \
    SEQUENCE=ai=0:at=221:ae=3:lu=100:lo=NNU:ei=324356:lr=1: \
    USERID=ID=291821 NO_USERS=1 GROUP=ONE id_info=324356 \
    CREATION_DATE=27-MAY-2012 SN=324356  KEY ="22WS \
    DE34 43RE 342E WSEW T54R HY67 TFRT 4ER4 WE23 XS21 \
    CD32 12QW"

BLOCK VICTOR DATE 01-JAN-2010 6 DEHDUESO203028DJE \
    SEQUENCE=ai=0:at=221:ae=3:lu=100:lo=NNU:ei=324356:lr=1: \
    USERID=ID=291821 NO_USERS=5 GROUP=ONE id_info=324356 \
    CREATION_DATE=27-MAY-2012 SN=324356  KEY ="22WS \
    DE34 43RE 342E WSEW T54R HY67 TFRT 4ER4 WE23 XS21 \
    CD32 12QW"

#--BLOCK--ENDS--HERE#
#--NEW--BLOCKS--CAN--BE--APPENDED--HERE--#      

我只对每个块的Block Name,NO_USERS和id_info感兴趣。 将这三个数据保存到数据结构(比如说dict),它进一步存储在一个列表中:

[{Name: IMPULSE ,NO_USER=3,id_info=1021055},{Name: PASSION ,NO_USER=1,id_info=324356}. . . ]

任何其他可以保存信息的数据结构也没问题。

到目前为止,我已经尝试通过逐行阅读来获取块名称:

fOpen = open('DATA.txt')
unique =[]
for row in fOpen:
    if "BLOCK" in row:
        unique.append(row.split()[1])
print unique

我正在考虑正则表达式方法,但我不知道从哪里开始。 任何帮助将是欣赏。同时我也在尝试,如果我得到的东西会更新。请帮忙。

1 个答案:

答案 0 :(得分:1)

您可以使用groupy查找每个块,使用正则表达式提取信息并将值放在dicts中:

from itertools import groupby
import re


with open("test.txt") as f:
    data = []
    # find NO_USERS= 1+ digits or id_info= 1_ digits
    r = re.compile("NO_USERS=\d+|id_info=\d+")
    grps = groupby(f,key=lambda x:x.strip().startswith("BLOCK"))
    for k,v in grps:
        # if k is True we have a block line
        if k:
            # get name after BLOCK
            name = next(v).split(None,2)[1]
            # get lines after BLOCK and get the second of those
            t = next(grps)[1]
            # we want two lines after BLOCK
            _, l = next(t), next(t)
            d = dict(s.split("=") for s in r.findall(l))
            # add name to dict
            d["Name"] = name
            # add sict to data list
            data.append(d)

print(data)

输出:

 [{'NO_USERS': '3', 'id_info': '1021055', 'Name': 'IMPULSE'},
 {'NO_USERS': '1', 'id_info': '324356', 'Name': 'PASSION'}, 
{'NO_USERS': '5', 'id_info': '324356', 'Name': 'VICTOR'}]

或者没有groupby,因为你的文件遵循格式我们只需要在BLOCK行之后提取第二行:

with open("test.txt") as f:
    data = []
    r = re.compile("NO_USERS=\d+|id_info=\d+")
    for line in f:
        # if True we have a new block
        if line.startswith("BLOCK"):
            # call next twice to get thw second line after BLOCK
            _, l = next(f), next(f)
            # get name after BLOCK
            name = line.split(None,2)[1]
            # find our substrings from l 
            d = dict(s.split("=") for s in r.findall(l))
            d["Name"] = name
            data.append(d)

print(data)

输出:

[{'NO_USERS': '3', 'id_info': '1021055', 'Name': 'IMPULSE'}, 
{'NO_USERS': '1', 'id_info': '324356', 'Name': 'PASSION'}, 
{'NO_USERS': '5', 'id_info': '324356', 'Name': 'VICTOR'}]

要提取您可以迭代的值:

for dct in data:
    print(dct["NO_USERS"])

输出:

3
1
5

如果你想要一个dicts的dict并从1-n访问每个部分,你可以使用1-n作为tke键存储为嵌套的dicts:

from itertools import  count
import re

with open("test.txt") as f:
    data, cn = {}, count(1)
    r = re.compile("NO_USERS=\d+|id_info=\d+")
    for line in f:
        if line.startswith("BLOCK"):
            _, l = next(f), next(f)
            name = line.split(None,2)[1]
            d = dict(s.split("=") for s in r.findall(l))
            d["Name"] = name
            data[next(cn)] = d
   data["num_blocks"] = next(cn) - 1

输出:

from pprint import pprint as pp

pp(data)
{1: {'NO_USERS': '3', 'Name': 'IMPULSE', 'id_info': '1021055'},
 2: {'NO_USERS': '1', 'Name': 'PASSION', 'id_info': '324356'},
 3: {'NO_USERS': '5', 'Name': 'VICTOR', 'id_info': '324356'},
 'num_blocks': 3}

'num_blocks'会告诉您确切的块数。