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

Python筛选f.txt中不作为x.txt行前缀的行并输出到新文件

Python实现TXT接口前缀匹配筛选

需求说明

现有两个txt文件,需要筛选出f.txt中没有作为x.txt任意行前缀的行,将结果输出到新的txt文件中。

f.txt内容

interface Eth-Trunk50
interface Eth-Trunk51
interface Eth-Trunk60
interface Eth-Trunk60.2535
interface Eth-Trunk100
interface GigabitEthernet0/0/0
interface GigabitEthernet1/1/1
interface GigabitEthernet1/1/4
interface GigabitEthernet1/1/10

x.txt内容

interface Eth-Trunk50.1000
interface Eth-Trunk50.1030
interface Eth-Trunk51.2071
interface Eth-Trunk51.2072
interface Eth-Trunk100.108
interface Eth-Trunk100.109
interface Eth-Trunk100.111
interface GigabitEthernet1/1/0
interface GigabitEthernet1/1/1.660
interface GigabitEthernet1/1/1.662
interface GigabitEthernet1/1/2
interface GigabitEthernet1/1/10.3400
interface GigabitEthernet1/1/10.3600
interface GigabitEthernet1/1/10.3800
interface GigabitEthernet2/1/1
interface GigabitEthernet2/1/1.3010

期望输出结果

interface Eth-Trunk60
interface Eth-Trunk60.2535
interface GigabitEthernet0/0/0
interface GigabitEthernet1/1/4

原代码问题点

  1. 文件遍历逻辑错误:x.txt的文件指针在第一次循环后就走到了末尾,后续遍历f.txt的行时,不会再读取x.txt的内容
  2. 判断逻辑颠倒:原代码只要碰到x.txt有一行不是以当前f.txt行开头就直接输出,正确逻辑应该是x.txt所有行都不以当前f.txt行开头时才输出

修正后代码

def readB(Devices):
    # 读取f.txt所有行
    f_lines = []
    f_path = f'C:/Users/Ahmed Shouaib/Downloads/Backup Configurtion files/{Devices}-NO trust upstream default33.txt'
    with open(f_path, 'r', encoding='utf-8') as f:
        f_lines = [line.strip() for line in f if line.strip()]
    
    # 提前读取x.txt所有行,避免重复遍历文件
    x_lines = []
    x_path = f'C:/Users/Ahmed Shouaib/Downloads/Backup Configurtion files/{Devices}-NO trust upstream default55.txt'
    with open(x_path, 'r', encoding='utf-8') as x:
        x_lines = [line.strip() for line in x if line.strip()]
    
    out_path = f'C:/Users/Ahmed Shouaib/Downloads/Backup Configurtion files/{Devices}-NO trust upstream default66.txt'
    with open(out_path, 'w', encoding='utf-8') as new:
        for n in f_lines:
            # 检查是否存在任意一条x的行以n为前缀
            has_prefix = any(line.startswith(n) for line in x_lines)
            if not has_prefix:
                print(n)
                new.write(n + '\n')

readB('10.0.130.13')

内容的提问来源于stack exchange,提问作者Ahmed Shouaib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:45:03