【发布时间】:2014-06-30 17:41:17
【问题描述】:
我试图在从目录中打开某些文件后调用一个函数来解析文件。我需要在函数中打开文件吗?使用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
【问题讨论】:
-
你到底有什么问题?错误信息?然后发布(包括完整的回溯)。您没有收到任何错误,但结果不是您所期望的?告诉我们你得到了什么,你期望什么。帮助我们帮助您。
-
@kindall 没有错误消息,在调用函数时它似乎不起作用,但在使用 if 语句作为代码中的注释时工作正常。我想要的是打开目录中的某个文件,循环打开多个文件,解析它并打印调用函数的匹配单词/行。如果您需要更多详细信息,请告诉我。谢谢
-
“它似乎不起作用”正是我所说的那种事情。 :-(
标签: python file function file-io