Python熊猫read_csv
这样单独编写时会提供正确的输出:
import pandas as pd
def bgp_neighbor_status():
data = pd.read_csv('E:\\Python-Scripts\\bgp-result.txt', delim_whitespace=True, header=None)
for index, row in data.iterrows():
if row[9] == 'Down' or row[9] == 'Idle' or row[9] == 'Active':
print(f"Neighbor {row[0]} is down")
else:
pass
bgp_neighbor_status()
按预期显示的输出:
Neighbor 10.0.11.101 is down
但是,当我将相同的功能与这样的另一个功能结合使用时,出现错误:- pandas.errors.EmptyDataError:没有要从文件中解析的列
from __future__ import print_function
from netmiko import ConnectHandler
import pandas as pd
import sys
import time
import select
import paramiko
import re
bgp_result_file = open(r'E:\\Python-Scripts\\bgp-result.txt','w')
old_stdout = sys.stdout
sys.stdout = bgp_result_file
platform = 'cisco_ios'
username = 'javed'
password = 'cisco'
ip_add_file = open(r'E:\\Python-Scripts\\IPAddressList.txt', 'r')
def check_bgp(ip_add_file):
for host in ip_add_file:
host = host.rstrip('\n')
connect = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = connect.send_command('terminal length 0')
output = connect.send_command('enable')
bgp_status = connect.send_command('show ip bgp summary | be N')
print (bgp_status)
def bgp_neighbor_status():
data = pd.read_csv('E:\\Python-Scripts\\bgp-result.txt', delim_whitespace=True, header=None)
for index, row in data.iterrows():
if row[9] == 'Down' or row[9] == 'Idle' or row[9] == 'Active':
print(f"Neighbor {row[0]} is down")
else:
pass
check_bgp(ip_add_file)
bgp_neighbor_status()
答案 0 :(得分:1)
此行位于顶部:
bgp_result_file = open(r'E:\\Python-Scripts\\bgp-result.txt','w')
该行在脚本的开头执行,基本上清除了文件。根据文档:https://docs.python.org/2/library/functions.html#open
最常用的mode值是'r'表示读取,'w'表示写(如果文件已经存在,则将其截断),以及'a'表示附加(在某些Unix系统上,这意味着所有写操作都会附加到文件末尾,无论当前搜索位置如何)。 [...]
截断文件(如果已经存在)。