Python文件指定行删除功能异常求助:无法排除目标行
问题描述
我编写了一段Python代码,想要实现重写文件并排除指定行的功能,但运行后目标行无法被识别并排除。
我的代码:
def removal(i): with open(r"D:\Largecodefile\Customer.txt", "r") as f: lines = f.readlines() h,j = i-2,i-1 data1, data2 = lines[h],lines[j] print('data is ',data1,'and',data2) print('line is ',lines) with open(r"D:\Largecodefile\Customer.txt", "w") as f: for line in lines: if line.strip('\n') != data1 and data2: f.write(line)
当前运行输出的行列表:
line is ['JSJSJSJSJS\n', '10-02-1975\n', 'HAHAHAHAHA\n', '26-11-2001\n', 'BOTBOITBOT\n', '13-09-2018\n', 'Phill\n', 'Gill']
data1和data2的输出:
data is Phill\n and Gill
从输出看目标行与列表完全匹配,但代码无法识别排除,我怀疑问题出在倒数第二行,试过仅排除单行、去除换行符等操作都没解决,恳请帮助!
问题分析与解决方案
问题确实出在条件判断行if line.strip('\n') != data1 and data2:,存在两个核心错误:
- 逻辑判断写法错误:
and两侧需要完整的条件表达式,当前写法等价于(line.strip('\n') != data1) and data2,而data2是非空字符串,会被视为True,导致条件几乎始终成立,所有行都会被写入文件。 - 字符串匹配不一致:
data1包含换行符\n,但line.strip('\n')已经去掉了换行符,两者无法匹配(比如data1是Phill\n,处理后的行是Phill)。
修正方案一:统一处理换行符后匹配
def removal(i): with open(r"D:\Largecodefile\Customer.txt", "r") as f: lines = f.readlines() h, j = i-2, i-1 data1, data2 = lines[h], lines[j] # 先处理目标行的换行符,统一匹配规则 target1 = data1.strip('\n') target2 = data2.strip('\n') print('data is ', data1, 'and', data2) print('line is ', lines) with open(r"D:\Largecodefile\Customer.txt", "w") as f: for line in lines: current_line = line.strip('\n') # 明确判断当前行不属于两个目标行 if current_line != target1 and current_line != target2: f.write(line)
修正方案二:直接匹配原行(更简洁高效)
def removal(i): with open(r"D:\Largecodefile\Customer.txt", "r") as f: lines = f.readlines() h, j = i-2, i-1 # 把要排除的行存入集合,利用集合的快速查找特性 exclude_lines = {lines[h], lines[j]} print('data is ', lines[h], 'and', lines[j]) print('line is ', lines) with open(r"D:\Largecodefile\Customer.txt", "w") as f: for line in lines: if line not in exclude_lines: f.write(line)
两种方案都能解决问题:
- 方案一通过统一去除换行符,避免了因换行符导致的匹配失败;
- 方案二直接对比
readlines()读取的原行(包含换行符,最后一行可能无换行符),逻辑更直接,效率更高。
内容的提问来源于stack exchange,提问作者V21
相关产品推荐
相关产品推荐

