迭代文件保存块和跳过行

2024-04-27 02:58:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有块中的数据,块之间有非数据线。这段代码一直在工作,但不是健壮的。如何在索引测试中提取块并跳过非数据块而不占用一行?我正在寻找一个没有加载包的直接python解决方案。你知道吗

我已经搜索了一个相关的例子,如果答案存在,我很乐意删除这个问题。你知道吗

from __future__ import print_function

BLOCK_DATA_ROWS = 3
SKIP_ROWS = 2
block = 0

with open('array1.dat', 'rb') as f:
    for i in range (2):
        block += 1
        for index, line in enumerate(f):
            if index == BLOCK_DATA_ROWS:
                break
            print(block, 'index', index, 'line', line.rstrip('\r\n'))

        for index, line in enumerate(f):
            if index == SKIP_ROWS:
                break
            print('  skip index', index, 'line', line.rstrip('\r\n'))

输入

1
2
3
4
5
6
7
8
9

输出

1 index 0 line 1
1 index 1 line 2
1 index 2 line 3
  skip index 0 line 5
  skip index 1 line 6
2 index 0 line 8
2 index 1 line 9

编辑

我还想对excel工作表使用类似的迭代方法:

for row in ws.iter_rows()

Tags: 数据infordataindexiflineblock
1条回答
网友
1楼 · 发布于 2024-04-27 02:58:00

在发布的代码中,读取第4行,满足条件index == BLOCK_DATA_ROWS,使第一个循环朝向第二个循环。由于f是一个generator,当在第二个循环中调用它时,它返回要迭代的下一个元素,并且第4行已经返回到循环1(它没有被打印,但是使用了值)。你知道吗

代码中必须考虑到这一点。一种选择是在同一个循环中组合两个条件:

from __future__ import print_function

BLOCK_DATA_ROWS = 3
SKIP_ROWS = 2
block = 1

with open('array1.dat', 'r') as f:
    index = 0
    for line in f:
        if index < BLOCK_DATA_ROWS:
            print(block, 'index', index, 'line', line.rstrip('\r\n'))
        elif index < BLOCK_DATA_ROWS+SKIP_ROWS:
            print('  skip index', index, 'line', line.rstrip('\r\n'))
        index += 1
        if index == BLOCK_DATA_ROWS+SKIP_ROWS: # IF!!, not elif
            index = 0
            block += 1

for i in range(2)也被删除了,现在代码可以处理任意数量的块,而不仅仅是2个。你知道吗

返回:

1 index 0 line 1
1 index 1 line 2
1 index 2 line 3
  skip index 3 line 4
  skip index 4 line 5
2 index 0 line 6
2 index 1 line 7
2 index 2 line 8
  skip index 3 line 9
  skip index 4 line 10

相关问题 更多 >