2016-12-14 4 views
0
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 

Петли итерацию только для одного файла и выполнения останавливаются, я хотел, чтобы перебрать все файлы в каталогепечать имен всех файлов, которые содержат эту строку

+1

@ironfist Ваше редактирование сделало нерегулярную отступом, но загружала программу в нечто, что бросает IndentationError при загрузке. – Anthon

ответ

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 в них).

1

os.listdir (путь)

Верните список, содержащий имена записей в каталоге, заданном путем. Список находится в произвольном порядке. Он не включает специальные записи '.' и «..», даже если они присутствуют в каталоге.

listdir возвращает файлы и каталоги, Вы должны проверить, что переменная file файл или каталог.

Использование os.path.isfile

os.path.isfile (путь)

Возвращает True, если путь существующий обычный файл. Это следует за символическими ссылками, поэтому оба islink() и isfile() могут быть истинными для одного и того же пути.

В вашем случае:

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 
Смежные вопросы