从文件中删除一行及其上一行

2024-09-24 08:27:46 发布

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

我有以下文件:

>Line1
Some contents of line 1
>Line2
------Some contents I don't need
>Line3
More content of line 3

我尝试删除以---开头的行以及前一行,结果如下:

>Line1
Some contents of line 1
>Line3
More content of line 3

这是我当前的代码,目前我只能删除以---开头的行,但不能删除它前面的行:

with open("test.txt") as f1:
    for lines in f1:
        if lines.startswith("---"):
            pass
        else:
            print(lines)

Tags: 文件of代码morelinecontentssomecontent
3条回答

这里有一个建议:

with open ("test.txt") as f:
   line1 = f.readline()
   while line1:
      line2 = f.readline()
      if not line2.startswith("---"):
         print(line1,"\n",line2)
      line1 = f.readline()

这是我能想到的最具可读性的解决方案

with open("test.txt") as lines:
    # initial value (relevant for first line only)
    last_line = next(lines)
    last_line_started_with_dashes = False

    for line in lines:
        this_line_starts_with_dashes = line.startswith("---")

        if not (last_line_started_with_dashes or this_line_starts_with_dashes):
            print(last_line)

        # prepare for next iteration
        last_line_started_with_dashes = this_line_starts_with_dashes
        last_line = line

您可以尝试此脚本不打印以---开头的行及其前面的行:

with open("file.txt", "r") as f1:
    i = map(str.strip, f1)
    prev_line = next(i)
    for line in i:
        if line.startswith('---'):
            prev_line = next(i, '')
            continue
        print(prev_line)
        prev_line = line
    print(prev_line)

相关问题 更多 >