shell 跳过每隔一行阅读文本文件的Python

sxissh06  于 2023-03-09  发布在  Shell
关注(0)|答案(1)|浏览(151)

我正在用Python处理一个shell脚本。我的第一步是梳理文件,并只将重要的行保存在一个(字符串)列表中。然而,我隔离了一个问题,即每隔一行都被忽略。为什么在下面的代码中第二行、第四行等被跳过?

f = open("sample_failing_file.txt", encoding="ISO-8859-1")
readfile = f.read()
filelines = readfile.split("\n")

def remove_irrelevant_lines(filecontent: list[str]) -> list[str]:
    for line in filecontent:
        if drop_line_appropriate(line):
            filecontent.remove(line)
    return filecontent

def drop_line_appropriate(line: str) -> bool:
    if line.startswith("#"):
        return True
    # some more conditions, omitted here
    return False

filelines = remove_irrelevant_lines(filelines)
f.close()

当我运行这段代码时,我可以看到filecontent是完整的。但是,当我查看line时,我可以看到例如some line 3从未被读取。这是shell脚本的简化版本,我的Python脚本在该版本上失败(sample_failing_file. txt)

#!/bin/sh
#
# some line 1
#
# some line 2
# some line 3
vsaztqbk

vsaztqbk1#

正如注解中指出的,在迭代列表时,不应该尝试从列表中删除元素,另外,删除行时,不要使用list.remove(),因为这会导致它搜索行,这将使它的运行速度大大低于它应该运行的速度。
下面的代码应该可以解决您的问题,并且运行速度也会大大加快:

def remove_irrelevant_lines(filecontent: list[str]) -> list[str]:
    return [line for line in filecontent if not drop_line_appropriate(line)]

这将创建并返回一个新列表,过滤掉drop_line_appropriate指示的行。

相关问题