Python 在文件夹和子文件夹中复制搜索文件
我试图在目录树中查找文件列表。本质上,我提供了一个文本文件,其中包含我要搜索的所有术语(~500),并让它在目录和子目录中查找它们。但是,我相信,我对代码所采取的步骤有问题,并且在没有搜索所有文件夹的情况下过早结束 我使用的代码是(Python 在文件夹和子文件夹中复制搜索文件,python,file,search,directory,Python,File,Search,Directory,我试图在目录树中查找文件列表。本质上,我提供了一个文本文件,其中包含我要搜索的所有术语(~500),并让它在目录和子目录中查找它们。但是,我相信,我对代码所采取的步骤有问题,并且在没有搜索所有文件夹的情况下过早结束 我使用的代码是(pattern是文本文件的名称): 有没有关于我错在哪里的想法?问题的全部或部分可能是,除非您使用重置文件中的当前位置,否则您只能在文件中迭代一次 在再次尝试循环浏览文件之前,请确保查找回文件的开头: import os def locateA(pattern, r
pattern
是文本文件的名称):
有没有关于我错在哪里的想法?问题的全部或部分可能是,除非您使用重置文件中的当前位置,否则您只能在文件中迭代一次 在再次尝试循环浏览文件之前,请确保查找回文件的开头:
import os
def locateA(pattern, root):
file = open(pattern, 'r')
for path, dirs, files in os.walk(root):
for word in files:
file.seek(0) # this line is new
for line in file:
if line.strip() in word:
print os.path.join(path, word), line.strip()
for line in file
第一次使用file
中的行,之后每次都为空
请尝试此操作,它可以解决此问题和其他一些问题:
import os
def locateA(pattern, root):
patterns = open(pattern, 'r').readlines() # patterns is now an array, no need to reread every time.
for path, dirs, files in os.walk(root):
for filename in files:
for pattern in patterns:
if pattern.strip() in filename:
print os.path.join(path, filename), pattern.strip()
我建议使用带有open(模式,'rU')的构造
作为f:
,不要调用您的文件file
,因为file
是内置模块中的一个类。将文件名更改为其他名称。我将调查您提到的解释。那么问题的具体症状是什么?快速提问,为什么我需要代码中的filecontent=open(file,'r')。read()
?这会打开目录中的每个文件吗?很抱歉,我误解了你的问题,以为你想在每个文件中执行与grep
等效的操作。我现在看到你实际上在匹配文件名。我纠正了这个例子。啊哈!,看起来这很有效。我不知道你只能迭代onceNo问题,如果我的答案有帮助的话,你可以点击答案旁边复选标记的轮廓。
import os
def locateA(pattern, root):
patterns = open(pattern, 'r').readlines() # patterns is now an array, no need to reread every time.
for path, dirs, files in os.walk(root):
for filename in files:
for pattern in patterns:
if pattern.strip() in filename:
print os.path.join(path, filename), pattern.strip()