1

I have the task of creating a search program in python (or c++ or bash) I'm really not that experienced when it comes to coding so if this isn't on the right track at all, sorry!

The user will need to type in a keyword I.E "Report" and the function will need to look through all directories for files with the name of "report". This script I've made up here seems to work up until line 5. Could anyone help me out? Thank you!

import os

keyword = raw_input ("What would you like to search for?")

os.chdir("/home/noob")

for files in os.listdir("."):

  if files(keyword):

     print files
user2882612
  • 29
  • 1
  • 3

1 Answers1

1

I'm guessing you're getting a TypeError: 'list' object is not callable. That's because os.listdir returns a list of files.

What you want is to do one of the following:

if keyword in files: # for an exact match

Or

for filename in files:
    if keyword.lower() in filename.lower(): #for case insensitive searching
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • So after adding that in, I take it i'll need to define files to a directory like files = /home/noob – user2882612 Oct 15 '13 at 13:32
  • Aha brilliant it works! How easy would it be to add in where the files are located? So it tells you the directory it is in. I've obviously set it to look in /home/noob but say the file was in noob/documents/office/ how could i get the program to show me this? – user2882612 Oct 15 '13 at 13:47
  • Check out the `os` module and `os.path` (your favorite search engine should help out there). Especially of interest should be `os.path.abspath`. (Also, `>>> help(os.path.abspath)`, once you've done `import os`. – Wayne Werner Oct 15 '13 at 14:22