python - 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”的行上循环。
解决方案
您可以存储“行”和“列”行的索引,然后使用这些值来获取行和列值。您可以这样做:
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]
推荐阅读
- api - 如何生成谷歌翻译 API 密钥
- python - 有没有更好的方法来加快 Pandas 读取 csv 文件的速度?
- ionic-framework - 编码完成后如何发布 Angular-Ionic 应用到商店
- vba - MS-Access 表单显示数字,而不是加载时的名称
- ruby-on-rails - 从数据库中删除回形针图像/文件时,我可以证明找不到 404
- python - 如何在 R 代码中从 python 调用变量
- unity3d - unity改变粒子材质而不改变其他粒子系统
- sql - 带有 INSERT 的 CTE 有时会执行两次该语句
- excel - 从填充了 For Each 循环的表中删除过时的值?
- reactjs - 如何在chartjs回调页脚函数中添加html标签