针对整个文件目录执行功能

时间:2018-12-29 20:23:17

标签: python networking

如何最好地对文件目录运行一个函数(最终是多个函数)?在此特定示例中,我试图对每个文件分别运行该函数,因此只需要一次运行一个文件。从长远来看,我希望脚本能够更全面地检查事物,但现在一次就足够了。

在我当前的情况下,它将是网络设备的输出。例如,下面从交换机上的“显示cdp邻居详细信息”中获取输出,并稍微清理输出。

变量“ thefile”用于针对单个文件运行,但是我需要针对目录中任意数量的文件运行。多个脚本?这个脚本中有某种os.walk()代码吗?

hostcheck = "hostname"
devicecheck = "Device ID"
ipaddresscheck = "IP address"
platformcheck = "Platform"
interfacecheck = "Interface"
hyphencheck = "---"

thefile = "core-cdp-detail.log"

with open(thefile) as search:
    for line in search:
        line = line.rstrip()  # remove '\n' at end of line
        if hostcheck in line:
            hostentry = line.split("hostname ")[1]
            print("Below CDP information is from " + hostentry)
        elif devicecheck in line:
            print("Remote " + line)
        elif ipaddresscheck in line:
            print("Remote " + line.lstrip())
        elif platformcheck in line:
            print(line.split(",")[0])
        elif interfacecheck in line:
            print("Remote Interface: " + line.split("port):")[1])
        elif hyphencheck in line:
            print(line)
            print("\n")
            print("Local Device ID: " + hostentry)

2 个答案:

答案 0 :(得分:0)

import glob

for file in glob.glob('*.log'):
    with open(file) as search:
        ...

(或您要执行此操作的任何文件,都可以将'*.log'替换为'*.*''logs/*.log'等)

有关更多信息,请参见glob模块上的文档。

答案 1 :(得分:0)

您可以使用os.walk遍历目录

import os

hostcheck = "hostname"
devicecheck = "Device ID"
ipaddresscheck = "IP address"
platformcheck = "Platform"
interfacecheck = "Interface"
hyphencheck = "---"


def check_content(file_path):
    with open(thefile) as search:
        for line in search:
            line = line.rstrip()  # remove '\n' at end of line
            if hostcheck in line:
                hostentry = line.split("hostname ")[1]
                print("Below CDP information is from " + hostentry)
            elif devicecheck in line:
                print("Remote " + line)
            elif ipaddresscheck in line:
                print("Remote " + line.lstrip())
            elif platformcheck in line:
                print(line.split(",")[0])
            elif interfacecheck in line:
                print("Remote Interface: " + line.split("port):")[1])
            elif hyphencheck in line:
                print(line)
                print("\n")


def check_dir_content(dir_path):

    for subdir, dirs, files in os.walk(dir_path):
        for file in files:
            check_content(os.path.join(subdir, file))

if __name__ == '__main__':
    check_dir_content('/Users/gaurang.shah/Documents')