调用函数python fi

2024-10-02 08:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在打开目录中的某些文件后调用函数来解析文件。我需要在函数中打开文件吗?使用if语句,但不在调用函数时使用。Python新手无法使其工作。谢谢你,在其他问题上找不到答案。。。你知道吗

#!usr/bin/env/ python
import sys, re, os

#function to find the packetloss data in pcoip server files
def function_pcoip_packetloss(filename):
    lineContains = re.compile('.*Loss=.*')  #look for "Loss=" in the file
    for line in filename:
        if lineContains.match(line):    #check if line matches "Loss="
            print 'The file has: '  #prints if "Loss=" is found
            print line
            return 0;

#function to find the decrease in pcoip_server files
def function_pcoip_decrease(filename):
    lineContainsDecrease = re.compile('.*Decrease.*')
    for line in filename:
        if lineContainsDecrease.match(line):    #check if line matches "Decrease"
            print 'The file has: '          #prints if "Decrease is found"
            print line
            return 0;

for root, dirs, files in os.walk("/users/home10/tshrestha/brb-view/logs/vdm-sdct-agent/pcoip-logs"):
    lineContainsServerFile = re.compile('.*server.*')

    for filename in files:
        if lineContainsServerFile.match(filename):
            filename = os.path.join(root,filename)
            with open(filename,'rb') as files:
                #lineContainsLoss = re.compile('.*Loss=.*')
                filename = os.path.join(root,filename)
                for line in files:
                    function_pcoip_packetloss(files);
                    function_pcoip_decrease(files);
              #works with these if but when I call the function does not work
                #for line in files:
                    #if lineContainsLoss.match(line):
                        #print line

Tags: theinreforifosmatchline
1条回答
网友
1楼 · 发布于 2024-10-02 08:22:49

您混合了文件名和文件句柄的概念。在文件循环中使用文件并不是一个好办法。试试这个:

    for filename in files:
            if lineContainsServerFile.match(filename):
                    filename = os.path.join(root,filename)
                    with open(filename,'rb') as filehandle:
                         function_pcoip_packetloss(filehandle)
                         filehandle.seek(0)
                         function_pcoip_decrease(filehandle)

相关问题 更多 >

    热门问题