Python删除TXT空行,需移除指定末尾行且不使用readlines[:-1]方案
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
- Line Caching: We store each valid line in
cached_lineinstead of writing it right away. - 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).
- Final Validation: After the loop ends, we check if the last cached line meets your "complete" criteria (in your example, lines containing
testare 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
-, usecached_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

