Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6054559
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T08:09:59+00:00 2026-05-23T08:09:59+00:00

The elif stament should print the log files and path that were not found

  • 0

The elif stament should print the log files and path that were not found in a search that I conduct. However, they yield every line that is searched in a single file (a plethora of info). What am I doing wrong?

 for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
      result = regex.search(whitespace.sub('', line))
      if result:
          template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
          output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

          print output
          temp.write(output)
          break
      elif not result:
          template = "\nLine: {0}\nString not found in File: {1}\nString Type: {2}\n\n"
          output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

          print output
          temp.write(output)

  else:          
      print "There are no files in the directory!!!"

Actual Code:

 elif searchType =='2':
      print "\nDirectory to be searched: " + directory
      print "\nFile result2.log will be created in: c:\Temp_log_files."
      paths = "c:\\Temp_log_files\\result2.log"
      temp = file(paths, "w")
      userstring = raw_input("Enter a string name to search: ")
      userStrHEX = userstring.encode('hex')
      userStrASCII = ''.join(str(ord(char)) for char in userstring)
      regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
      goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n")


      def walk_dir(directory, extensions=""):
          for path, dirs, files in os.walk(directory):
             for name in files:
                if name.endswith(extensions):
                   yield os.path.join(path, name)

      whitespace = re.compile(r'\s+')
      for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
          result = regex.search(whitespace.sub('', line))
          if result:
              template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
              output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

              print output
              temp.write(output)
              #break
          elif result not in line:

              output = fileinput.filename()

              print output
              temp.write(output)
              break 

      else:          
          print "There are no files in the directory!!!"
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T08:10:00+00:00Added an answer on May 23, 2026 at 8:10 am

    You’re iterating over every line of every file passed to fileinput.input(...), right? And you perform the if statement for every line. If the condition is true, then you break, but if the condition is false, you don’t break, but write to temp. So for every line in fileinput.input that doesn’t match the condition, you write a line to temp and print output. (Actually, the above is wrong — see edit below.)

    Also, elif str(result) not in line: will have strange results — just use else as others have suggested. If result evaluates to false in this situation, then result == None, which means that str(result) == 'None', which means that if a line contains None, then you’ll have unexpected results.

    Edit: Ok, actually, looking more closely at your actual code the above is wrong, strictly speaking. But the point remains — fileinput.input() returns a FileInput object that in essence concatenates the files and iterates over every line in turn. Since in some cases you don’t want to perform an action per line, but per file, you’ll have to iterate over them individually. You could do this without fileinput but since that’s what you’re using, we’ll stick with that:

    for filename in walk_dir(directory, (".log", ".txt")):
        for line in fileinput.input(filename):
            result = regex.search(whitespace.sub('', line))
            if result:
                template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
                output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
                print output
                break   # (assuming you only want to print the first result)
        else:
            ouput = fileinput.filename()
            print output
            temp.write(output)
            break
    

    The way this works: for every file in the list, this prints the first match in the file, or prints the filename if no match was found. You can use else with a for loop in python; the else block at the end of the loop is executed if the loop is not broken. Since no match was found, the filename is printed.

    If you wanted to print out all matches in a file, you could save the matches in a list, and instead of using else, you could test the list. Simplified example:

    matches = []
    for line in fileinput.input(filename):
        if searchline(line):
            matches.append(line)
    if matches:
        print template.format(matches)
    else:
        print fileinput.filename()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How would you say "does not equal"? if hi == hi: print "hi" elif
i thought that elif: was the shorthand for else: if: but it's not possible
I have a code that has some mpi api-dependent bits: #if MPIVERSION==1 ... #elif
then, elif, else statement that I have programmed in a bash script. I know
According to the django 1.4 new features post, django should support elif tags in
if not sky.has_key('blue'): get_currently_compared_key # blue elif not sky.has_key('cloud'): get_currently_compared_key # cloud In above
I need to realize a complex if-elif-else statement in Python but I don't get
This piece of code gives a syntax error at the colon of elif process.loop(i,
I wrote a function in Python: def instantiate(c): if inspect.isclass(c): return c() elif isinstance(c,
For the example below: if a == 100: # Five lines of code elif

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.