import os
List = os.listdir("location of folder")
os.chdir("location of folder")
for file in List:
obj=open(file,"r")
while True:
line=obj.readline()
line=line.lower()
matchcount=line.count('automation',0,len(line))
if(matchcount>0):
print "File Name ----",obj.name
print "Text of the Line is ----",line
continue
循环只针对一个文件进行迭代,并且执行停止我希望它迭代目录中的所有文件
答案 0 :(得分:1)
os.listdir(路径)
返回包含条目名称的列表 path给出的目录。该列表按任意顺序排列。确实如此 不包括特殊条目'。'和'..'即使他们在场 在目录中。
listdir
返回文件和目录,您应该检查变量file
是文件或目录。
使用os.path.isfile
os.path.isfile(path)
如果path是现有常规文件,则返回True。 这遵循符号链接,因此islink()和isfile()都可以为true 为了同样的道路。
在你的案例中:
import os
location = {your_location}
List = os.listdir(location)
os.chdir(location)
for file in List:
if os.path.isfile(file):
obj = open(file, "r")
for line in obj.readlines():
line = line.lower()
matchcount = line.count('automation')
if matchcount > 0:
print "File Name ----", obj.name
print "Text of the Line is ----", line
continue
答案 1 :(得分:0)
可以对您的程序进行许多微小的改进。我会用评论重写它,以便我可以保持答案简短。
import os
import os.path
def find_grep(d, s): # Wrap this up as a nice function with a docstring.
"Returns list of files in directory d which have the string s"
files = os.listdir(d) # Use better names than "List"
matched_files = [] # List to hold matched file names
for f in files: # Loop over files
full_name = os.path.join(d, f) # Get full name to the file in question
if os.path.isfile(full_name): # We need to only look through files (skip directories)
with open(full_name) as fp:# Open the file
for line in fp:# Loop over lines of file
if s in line: # Use substring search rather than .count
matched_files.append(f) # Remember the matched file name
break # No need to loop through the rest of the file
return matched_files # Return a list of matched files
您可以像find_grep("/etc/", "root")
那样运行它(将在/etc
目录中找到其中包含字符串root
的所有顶级文件)。