在python中逐块读取文件

时间:2018-11-19 15:06:44

标签: python file

我有这种格式的文件

MACRO L20_FDPQ_TV1T8_1
 FIXEDMASK ;
 CLASS CORE ;
 ...
 ...
END L20_FDPQ_TV1T8_1
MACRO INV_20
...
...
END INV_20

我想将文件读取为块,以便每个MACRO到其名称末尾在python中形成一个块。我试图用这个

with open(file_name, "r") as f_read:
    lines = f_read.readlines()
num = 0
while num < len(lines):
    line = lines[num]
    if re.search(r"MACRO\s+", line, re.IGNORECASE):
            macro_name = line.split()[1]
            while re.search(r"\s+END\s+%s"%macro_name, line, re.IGNORECASE) is None:
                line = lines[num + 1]
                #...do something...
                num = num+1
            num +=1

如何有效地做到这一点?

1 个答案:

答案 0 :(得分:2)

假设您不能嵌套宏,则宏始终以“ MACRO [name]”开头,以“ END [name]”结尾:

# read the contents of the file
with open(file_name, "r") as f_read:
    lines = f_read.readlines()

current_macro_lines = []
for line in lines:
    if line.startswith("MACRO"):
        macro_name = line.split()[1]

    # if line starts with END and refers to the current macro name
    elif line.startswith("END") and line.split()[1] == macro_name:
        # here the macro is complete, 
        #put the code you want to execute when you find the end of the macro

        # then when you finish processing the lines, 
        # empty them so you can accumulate the next macro
        current_macro_lines = []

    else:
        # here you can accumulate the macro lines
        current_macro_lines.append(line)