【问题标题】:Python error os.walk IOErrorPython 错误 os.walk IOError
【发布时间】:2014-06-30 14:58:31
【问题描述】:

我试图用文件名中的服务器跟踪文件,我可以用服务器**打印目录中的所有文件,但是当我尝试读取文件时它给了我错误”说:

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);

【问题讨论】:

    标签: python file-io filepath


    【解决方案1】:

    文件是根目录中文件对象的名称。

    dirpath 是一个字符串,目录的路径。 dirnames 是 dirpath 中子目录名称的列表(不包括 '.' 和 '..')。 filenames 是 dirpath 中非目录文件的名称列表。请注意,列表中的名称不包含路径组件。要获取 dirpath 中文件或目录的完整路径(以 top 开头),请执行 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);
    

    【讨论】:

    • 感谢您的帮助,它似乎无法以这种方式工作,它只是打印 'filename' 并没有实际打印文件名。
    • 但它会打开正确的文件名使用 open(filename,'rb') 作为文件:
    • OK,去掉'filename'的引号,然后你就会得到这个变量的值。我会编辑答案。但重要的一点是正确的:您没有在尝试打开的文件名中包含目录路径。
    • 谢谢你们@holdenweb 我可以得到文件名,我以前也有,但是在调用函数时,它似乎不起作用。什么都没有发生,我试图解析文件并打印某些行...我试图找出原因,感谢您的帮助,谢谢
    【解决方案2】:

    os.walk() 函数是三元素元组的生成器。每个元组都包含一个目录作为其第一个元素。第二个元素是该目录中的子目录列表,第三个元素是文件列表。

    要生成每个文件的完整路径,必须连接第一个条目(目录路径)和第三个条目(文件)的文件名。最直接且与平台无关的方法是使用os.path.join()

    还要注意使用起来会更有效率

    lineContainsServerFile = re.compile('server')
    

    lineContainsServerFile.search() 而不是尝试匹配通配符字符串。即使在第一种情况下,尾随 ".* 也是多余的,因为 "server" 字符串后面的内容无关紧要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      相关资源
      最近更新 更多