如何跟踪文件python中的行

时间:2015-10-28 15:20:22

标签: python

我正在阅读python中的以下文件,如果该行= [FOR_RECORD],我想跟踪。那时我有一个for循环填充一个值为[REG_NAME]的输出,直到我到达[/ FOR_RECORD]。然后我想回到文件的[FOR_RECORD]部分的开头,开始填充下一个[REG_NAME]。我怎么能在像这样的python文件中跳转?

输入文件

--
--   generated with parser version 1.09
use ieee.std_logic_arith.all;

package [PKG_FILE]_pkg is

 [FOR_RECORD]
   constant [REG_NAME]_offset : std_logic_vector := x"[OFFSET]";
 [/FOR_RECORD]


 type [REG_NAME]_type is record
      [FILED_NAME]        : std_logic;               -- [OFFSET]     :
    end record [REG_NAME]_type;


 Package is [PKG_FILE]

Python代码

for line in input_1:
    if '[FOR_RECORD]' in line:
        # This is where I want to jump to the next line
        #So I can evaluate the contents

    # I have 4 names in reg_name[i]
    #Very important that this is nested in the if statement
        for x in range(0,4):   
            if '[/FOR_RECORD]' in line:
                break
            if '[REG_NAME]' in line:
                line=line.replace('[REG_NAME]',reg_name[i]['name'])
                output.write(line)    

    output.write(line)

3 个答案:

答案 0 :(得分:1)

您可以使用tell在文件中找到您的位置,seek转到特定位置,但您还必须使用readline函数,因为for循环会读取所有第一行。

input1 = open('file')
eof = False
while (True):
    while (True):
        line = input1.readline()
        if line == '':
            eof = True
            break
        output.write(line)
        if '[FOR_RECORD]' in line:
            offset = input1.tell()
            break

    if eof: break
    for i in range(4):
        input1.seek(offset)
        while (True):
            line = input1.readline()
            if line == '':
                eof = True
                break
            if '[/FOR_RECORD]' in line:
                break
            if '[REG_NAME]' in line:
                line=line.replace('[REG_NAME]',reg_name[i]['name'])
                output.write(line)
    if eof: break

第一个循环填充[FOR RECORD]行的位置,第二个循环遍历reg_name的元素。

答案 1 :(得分:0)

当您迭代文件时,可以使用next命令推进迭代器(检索下一行)。所以...这样的事情可能会让你到达你需要的地方:

for line in input_1:
  if '[FOR_RECORD]' in line:
    while '[/FOR_RECORD]' not in line:
      line = next(input_1)
      # your replacement code here.

这将迭代,直到找到你的开始标记,然后继续逐行消耗行,直到找到你的关闭标记,此时你将回退到外部for循环。

答案 2 :(得分:0)

我会使用迷你状态机。如果我们介于[FOR_RECORD][/FOR_RECORD]行之间,我们应该更换,而不是在外面。代码可以是:

in_record = False
for line in input_1:
    if '[FOR_RECORD]' in line:
        in_record = True
    elif '[/FOR_RECORD]' in line:
        in_record = False
    elif in_record:
        if '[REG_NAME]' in line:
            for i in range(4):
                output.write(line.replace('[REG_NAME]',
                              reg_name[i]['name']))
        else: output.write(line)
    else: output.write(line)