首页 > 解决方案 > Python - 从不同的起始行读取同一个文件

问题描述

我正在尝试读取文件(您可以在此处.non找到示例)。这些文件包含 4 个键:宽度、高度、行和列(两者都由多个值组成)。

宽度和高度总是在行、列或在我的情况下为目标之前,因此我必须浏览文件,同时不知道什么时候会找到我需要的东西。

这是我正在尝试做的事情:

# This function will create the grid
def fcreate(grid_id):
    gridfile = open(grid_id['grid'], "r")
    # Here, we're going through the entire file, getting the values we need.
    # Still working on a pretty way to make the dictionary !
    for line in gridfile:
        if "width" in line:
            grid_id['width'] = re.sub('[A-z]', '', line).strip()
        if "height" in line:
            grid_id['height'] = re.sub('[A-z]', '', line).strip()
        if "rows" in line:
            # Get all the rows values until something else ? Or EOF
        if "columns" in line:
            # Get all the columns values until something else ? Or EOF
    # end of the for
    gridfile.close()
    return grid_id
    pass

Grid_id包含我必须得到的所有值。

我已经尝试在“if”rows”中创建一个新的 for,一段时间等等,但似乎无法逃脱再次读取整个文件或在包含“rows”或“columns”的行上循环。

标签: python

解决方案


您可以存储“行”和“列”行的索引,然后使用这些值来获取行和列值。您可以这样做:

lines = gridfile.readlines()
for i,line in enumerate(lines):
    if "width" in line:
        grid_id['width'] = re.sub('[A-z]', '', line).strip()
    if "height" in line:
        grid_id['height'] = re.sub('[A-z]', '', line).strip()
    if "rows" in line:
        idx_rows = i
    if "columns" in line:
        idx_cols = i

width = int(grid_id['width'])
height = int(grid_id['height'])
rows = lines[idx_rows+1:idx_rows+1+height]
cols = lines[idx_cols+1:idx_cols+1+width]

推荐阅读