Saturday 3 December 2011

os.path.walk python example

Last week, I was interviewed by ignite solution recruitment team, I really enjoyed every part of it. During the interview process, I was needed to attend an online test. There are only three more questions on the test. I want to share one of the interesting question on the test with this blog post. Here is the question,

Write a program that accepts a string on the command line and prints out the list of files within a folder (or subfolders) that have the string within them.

Solution:
import os,re,sys
def fun(arg, dirname, fnmes):
    out_list = []
    for fname in fnmes:
        filepath = os.path.join(dirname,fname)
        if os.path.isfile(filepath):
            fp = open(filepath ,'r')
            text = fp.read()
            fp.close()
            if re.search(arg,text):
                # print full path. Calling os.path.basename will
                # give us just the name.
                print filepath

def main():
    strg=sys.argv[1]
    os.path.walk('.', fun, strg)

if __name__=='__main__':
    main()
Here is a simple os.path.walk() example which walks your directory tree and returns the list of file names that contains the given string.

3 comments:

  1. Here's my solution, with os.listdir():

    import os
    def index(directory):
    stack = [directory]
    files = []
    while stack:
    directory = stack.pop()
    for file in os.listdir(directory):
    fullname = os.path.join(directory, file)
    if search_term in fullname:
    files.append(fullname)
    if os.path.isdir(fullname) and not os.path.islink(fullname):
    stack.append(fullname)
    return files
    search_term = input('Enter a (part of) file name for search:')

    Modifying it to accepts a string on the command line only needs minimal corrections.

    ReplyDelete
  2. not clear why do you defined out_list in the function body

    ReplyDelete