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

Python检索Cisco配置文件指定IP遇编码错误及结果存文件求助

问题解决方法

错误原因

你遇到的UnicodeDecodeError是因为Python在Windows系统下打开文件时默认使用系统本地编码(你的环境里是cp874编码),但Cisco配置文件的编码和本地编码不匹配,导致解码失败。

优化后代码

直接用二进制模式读取文件匹配字符串,完全避免编码问题,同时实现结果写入文件:

import os

# 存储匹配到的文件名
matched_files = []
target = b'10.10.10.4'  # 转成字节串,适配二进制读取

for fname in os.listdir('.'):
    if os.path.isfile(fname):
        # 二进制模式读取,无需处理文件编码
        with open(fname, 'rb') as f:
            if target in f.read():
                matched_files.append(fname)
                print(fname)

# 将匹配结果写入到matched_files.txt
with open('matched_files.txt', 'w', encoding='utf-8') as f:
    for file in matched_files:
        f.write(file + '\n')

print(f"共找到{len(matched_files)}个符合条件的文件,结果已保存到matched_files.txt")

代码说明

  • 用rb二进制模式打开文件,把要匹配的IP转成字节串b'10.10.10.4',不需要处理文件编码,彻底规避解码错误
  • 用with语句自动管理文件句柄,不需要手动调用close(),避免资源泄漏
  • 所有匹配到的文件名先存在列表里,最后统一写入到matched_files.txt文件中
  • 如果你确定所有配置文件都是utf-8编码,也可以把打开配置文件的参数改成open(fname, 'r', encoding='utf-8', errors='ignore'),直接匹配普通字符串即可,也能解决报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:48:01