调用函数python文件

时间:2014-06-30 17:41:17

标签: python file function file-io

我正在尝试从目录中打开某些文件后调用一个函数来解析文件。我需要在函数中打开文件吗?使用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

1 个答案:

答案 0 :(得分:0)

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

    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)