Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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_Regex_Path - Fatal编程技术网

Python 我定义了搜索路径,但正在搜索其他文件夹中的文件

Python 我定义了搜索路径,但正在搜索其他文件夹中的文件,python,regex,path,Python,Regex,Path,有人能告诉我为什么下面的代码在指定路径中搜索子文件夹吗。我只想搜索c:\Python27中的所有.txt和.log文件。但是搜索显示了c:\Python27\Doc中.txt和.log文件的结果。。。等等等等。谢谢 elif searchType =='3': print "Directory to be searched: c:\Python27 " print " " directory = os.path.join("c:\\",

有人能告诉我为什么下面的代码在指定路径中搜索子文件夹吗。我只想搜索c:\Python27中的所有.txt和.log文件。但是搜索显示了c:\Python27\Doc中.txt和.log文件的结果。。。等等等等。谢谢

elif searchType =='3':
          print "Directory to be searched: c:\Python27 "
          print " "
          directory = os.path.join("c:\\","Python27")
          regex = re.compile(r'3[0-9]\d{10}')
          for root,dirname, files in os.walk(directory):
             for file in files:
               if file.endswith(".log") or file.endswith(".txt"):
                  f=open(os.path.join(root,file))
                  for line in f.readlines():
                      searchedstr = regex.findall(line)
                      for word in searchedstr:
                         print "String found: " + word
                         print "File: " + os.path.join(root,file)
                         break
                         f.close()
os.walk
是递归目录遍历-其文档说明:

在目录中生成文件名 也可以在树上行走 自上而下或自下而上

所以你得到了你想要的;-)

如果不需要递归,只需使用
os.listdir
。由于默认情况下,
os.walk
是自上而下的,因此您也可以在第一个目录之后剪切循环,但这很麻烦
os.listdir
很简单:

>>> for filename in  os.listdir(r"c:\python26\\"):
...   if filename.endswith('.txt') or filename.endswith('.log'): print filename
... 
lxml-wininst.log
MySQL-python-wininst.log
py2exe-wininst.log
PyXML-wininst.log
scons-wininst.log
os.walk
是递归目录遍历-其文档说明:

在目录中生成文件名 也可以在树上行走 自上而下或自下而上

所以你得到了你想要的;-)

如果不需要递归,只需使用
os.listdir
。由于默认情况下,
os.walk
是自上而下的,因此您也可以在第一个目录之后剪切循环,但这很麻烦
os.listdir
很简单:

>>> for filename in  os.listdir(r"c:\python26\\"):
...   if filename.endswith('.txt') or filename.endswith('.log'): print filename
... 
lxml-wininst.log
MySQL-python-wininst.log
py2exe-wininst.log
PyXML-wininst.log
scons-wininst.log