如何实现移除文件开头与结尾的所有空行(已完成开头空行移除,需补充结尾处理逻辑)
解决移除文件首尾空行(保留中间空行)的问题
你的现有代码已经能处理开头的空行,但因为是逐行即时输出,无法预判后续是否还有非空行,所以没法处理结尾的空行。要实现需求,我们需要先把所有行加载到内存中,再处理首尾的空行,最后输出剩余内容。
修改后的完整代码
#!/usr/bin/env python3 import sys import argparse import logging parser = argparse.ArgumentParser() parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin) parser.add_argument( '-d', '--debug', help="Print lots of debugging statements", action="store_const", dest="loglevel", const=logging.DEBUG, default=logging.WARNING, ) parser.add_argument( '-v', '--verbose', help="Be verbose", action="store_const", dest="loglevel", const=logging.INFO, ) args = parser.parse_args() if sys.stdin.isatty() and args.infile.name == "<stdin>": sys.exit("Please give some input") logging.basicConfig(level=args.loglevel) # Business Logic Here # 读取所有行到内存,保留每行的原始换行符 lines = args.infile.readlines() # 移除开头的空行:找到第一个非空行的索引 start_idx = 0 while start_idx < len(lines) and not lines[start_idx].strip(): start_idx += 1 # 移除结尾的空行:找到最后一个非空行的索引 end_idx = len(lines) - 1 while end_idx >= start_idx and not lines[end_idx].strip(): end_idx -= 1 # 输出处理后的内容,用end=''避免重复添加换行符(因为lines中的行已经包含换行) for line in lines[start_idx:end_idx+1]: print(line, end='')
关键修改点解释
- 读取所有行到内存:使用
readlines()一次性读取所有行,这样我们可以前后遍历判断首尾的空行。 - 定位开头非空行:从列表头部开始,跳过所有空行(通过
strip()判断是否为空),直到找到第一个非空行的索引。 - 定位结尾非空行:从列表尾部开始反向遍历,跳过所有空行,直到找到最后一个非空行的索引。
- 输出处理后的行:通过切片
lines[start_idx:end_idx+1]获取需要保留的内容,用print(line, end='')避免重复输出换行符(因为原文件的每行已经自带换行符)。
边界情况处理
- 如果文件全是空行:
start_idx会大于end_idx,此时不会输出任何内容,符合预期。 - 如果文件没有首尾空行:处理后的内容和原文件完全一致。
内容的提问来源于stack exchange,提问作者Ahmad Ismail
相关产品推荐
相关产品推荐

