Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取目录的输入_Python - Fatal编程技术网

Python 如何获取目录的输入

Python 如何获取目录的输入,python,Python,我要做的是在一个日志文件目录中搜索,它的开头是“filename001.log”,一个目录中可能有100个文件 我要针对每个文件运行的代码是检查日志的第8个位置是否始终包含数字。我怀疑一个非数字正在脱离我们的解析器。下面是一些简单的代码,我正在尝试检查: # import re from urlparse import urlparse a = '/folderA/filename*.log' #<< currently this only does 1 file b = '/fo

我要做的是在一个日志文件目录中搜索,它的开头是“filename001.log”,一个目录中可能有100个文件

我要针对每个文件运行的代码是检查日志的第8个位置是否始终包含数字。我怀疑一个非数字正在脱离我们的解析器。下面是一些简单的代码,我正在尝试检查:

# import re
from urlparse import urlparse

a = '/folderA/filename*.log' #<< currently this only does 1 file
b = '/folderB/' #<< I'd like it to write the same file name as it read
with open(b, 'w') as newfile, open(a, 'r') as oldfile:
    data = oldfile.readlines()
    for line in data:
        parts = line.split()
        status = parts[8]  # value of 8th position in the log file
        isDigit = status.isdigit()

        if isDigit = False:
                print " Not A Number :",status
                newfile.write(status)
#重新导入
从URLPRASE导入URLPRASE

a='/folderA/filename*.log'#要读取一个目录中与给定模式匹配的文件并写入另一个目录,请使用和
os.path
函数构造输出文件:

srcpat = '/folderA/filename*.log'
dstdir = '/folderB'
for srcfile in glob.iglob(srcpat):
   if not os.path.isfile(srcfile): continue

   dstfile = os.path.join(dstdir, os.path.basename(srcfile))
   with open(srcfile) as src, open(dstfile, 'w') as dst:
       for line in src:
           parts = line.split()
           status = parts[8]  # value of 8th position in the log file
           if not status.isdigit():
               print " Not A Number :", status
               dst.write(status)  # Or print >>dst, status if you want newline
这将创建空文件,即使没有发现错误条目。您可以等到处理完文件(并且关闭带有
块),然后检查输出的文件大小,如果为空则将其删除,或者您可以采用惰性方法,在开始迭代之前无条件删除输出文件,但不打开它;只有当你得到一个错误的值时,你才会打开这个文件(用append而不是write来保持先前循环的输出不被丢弃),对它进行写入,允许它关闭

  • 导入os并对os.listdir('path')中的文件名使用:
    。这将列出目录中的所有文件,包括子目录

  • 只需用正确的路径打开第二个文件。由于您已经有了使用上述方法进行迭代的文件名,因此只需替换目录即可。为此,您可以使用
    os.path.join


  • 也许这会帮助你获得当前目录下所有文件的列表,然后一个接一个地读取。当他们只需要一个目录中的文件,而不需要整个目录树时,为什么还要麻烦使用
    os.walk
    ?当他们为每个输入文件生成一个输出文件时,为什么要使用附加模式(如果使用了一个共享的输出文件并重新打开了,当然了,但不是吗?)。