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"行中创建一个新的for,有一段时间等等,但似乎无法逃脱再次读取整个文件或在包含"行"或"列"的行上循环。

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

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]

最新更新