Python 错误 os.walk IOError
我试着找到文件名中带有“server”的文件,并且我可以打印出目录中所有带有“server”的文件。但是当我尝试读取这个文件时,它给我报错,提示如下:
Traceback (most recent call last):
File "view_log_packetloss.sh", line 27, in <module>
with open(filename,'rb') as files:
IOError: [Errno 2] No such file or directory: 'pcoip_server_2014_05_19_00000560.txt'
我看到有类似的问题被提问过,但我还是没法解决我的问题。有些错误是通过使用chdir命令来改变当前目录到文件所在的目录来修复的。任何帮助都非常感谢。谢谢!
#!usr/bin/env/ python
import sys, re, os
#fucntion 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;
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):
with open(filename,'rb') as files:
print 'filename'
function_pcoip_packetloss(filename);
2 个回答
0
os.walk()
这个函数可以生成包含三个元素的元组。每个元组的第一个元素是一个目录,第二个元素是这个目录下的子目录列表,第三个元素是文件列表。
要生成每个文件的完整路径,需要把第一个元素(目录路径)和第三个元素中的文件名连接起来。最简单、最通用的方法是使用 os.path.join()
。
另外,使用
lineContainsServerFile = re.compile('server')
和 lineContainsServerFile.search()
会比尝试匹配一个通配符字符串要高效得多。即使在第一个情况下,后面的 ".*
也是多余的,因为在 "server"
字符串后面的内容并不重要。
1
这些文件是根目录下文件对象的名字。
dirpath 是一个字符串,表示目录的路径。dirnames 是 dirpath 中子目录名字的列表(不包括 '.' 和 '..')。filenames 是 dirpath 中非目录文件名字的列表。需要注意的是,这些列表中的名字不包含路径信息。如果你想得到 dirpath 中某个文件或目录的完整路径(以顶层目录开始),可以使用 os.path.join(dirpath, name) 来实现。
试试这个
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:
print 'filename:', filename
function_pcoip_packetloss(filename);