简体   繁体   中英

print names of all the files which contain this string

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

The loop is iterating only for one file and execution is stopped I wanted it to iterate over all files in a directory

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

listdir returns files and directories, You should check that the variable file is a file or directory.

Use os.path.isfile

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

In your Case:

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

There are lots of tiny improvements that can be made to your program. I'll rewrite it with comments so that I can keep the answer short.

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

You can run it like so find_grep("/etc/", "root") (will find all top level files in the /etc directory that have the string root in them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM