Skip to content Skip to sidebar Skip to footer

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.lowe

Solution 1:

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

Solution 2:

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).


Post a Comment for "Print Names Of All The Files Which Contain This String"