You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python删除TXT空行,需移除指定末尾行且不使用readlines[:-1]方案

How to Remove Incomplete Trailing Lines Without Blindly Deleting the Last Line in Python

Problem Context

I have a test.txt file with content like this:

1 - test
2 -
3 - test
4 -

My current Python code is:

with open('test.txt') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not line.strip():
            continue # 跳过空行
        outfile.write(line)

But the generated output.txt ends up with:

1 - test
2 -
3 -

I want to remove this trailing incomplete line, but I don't want to use approaches like lines = file.readlines(); lines = lines[:-1] that directly delete the last line. How can I achieve this?


Solution: Use Delayed Writing with Line Caching

Instead of writing lines immediately, we can cache each valid line and only write it once we’ve confirmed there’s a next line (or verify it’s a complete line after the loop ends). This way, we avoid writing incomplete trailing lines without blindly trimming the last line.

Here’s the adjusted code tailored to your example:

with open('test.txt') as infile, open('output.txt', 'w') as outfile:
    cached_line = None
    for line in infile:
        stripped_line = line.strip()
        if not stripped_line:
            continue  # 跳过空行
        
        # Write the cached line if we have one (this is the "previous" valid line)
        if cached_line is not None:
            outfile.write(cached_line)
        
        # Update the cache with the current valid line
        cached_line = line
    
    # After the loop, check if the final cached line is complete
    # Adjust this condition to match your definition of a "complete" line
    if cached_line is not None and 'test' in cached_line.strip():
        outfile.write(cached_line)

How This Works

  1. Line Caching: We store each valid line in cached_line instead of writing it right away.
  2. Delayed Writing: When we read a new valid line, we first write the cached previous line—this ensures we only write lines that are followed by another valid line (we’ll handle the last line separately).
  3. Final Validation: After the loop ends, we check if the last cached line meets your "complete" criteria (in your example, lines containing test are complete). If it does, we write it; if not, we skip it.

You can tweak the final validation condition to fit your actual needs:

  • If you need lines to not end with - , use cached_line.strip().endswith('-') is False
  • If you have a specific pattern, use a regex check like import re; re.match(r'\d+ - test', stripped_line)

内容的提问来源于stack exchange,提问作者William Rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:19:41