Python实现删除文本文件中第1/2列含奇数的行
删除文本中第1/2列含奇数的行的实现方法
Python 实现(通用跨平台)
直接逐行读取文件,筛选出两列均为偶数的行并保存:
input_file = "input.txt" output_file = "output.txt" with open(input_file, 'r') as infile, open(output_file, 'w') as outfile: for line in infile: columns = line.strip().split() if len(columns) < 2: continue try: col1 = int(columns[0]) col2 = int(columns[1]) if col1 % 2 == 0 and col2 % 2 == 0: outfile.write(line) except ValueError: continue
关键说明
- 若文件列用制表符分隔,将
split()改为split('\t') - 列数不足2列或列内容非数字的行直接跳过,可根据需求调整处理逻辑
- 核心逻辑:仅保留第1列和第2列均为偶数的行,等价于删除任意一列是奇数的行
Shell awk 实现(Linux/macOS 快速处理)
如果是在类Unix环境下,用awk命令更高效:
awk '$1 % 2 == 0 && $2 % 2 == 0' input.txt > output.txt
awk会自动按空白拆分列,满足条件的行直接输出到新文件,无需手动写循环。
内容的提问来源于stack exchange,提问作者RationalParadox
相关产品推荐
相关产品推荐

