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

  • Home
  • SEARCH
  • 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 6059383
In Process

The Archive Base Latest Questions

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

In the code below, the program is getting string data from the user and

  • 0

In the code below, the program is getting string data from the user and converting it to ascii and hex and searching all .log and .txt files in a certain directory for the string in plain string, hex, and ascii values. The program prints the line # , the string type found, and the file path if the string is found. However, not only do I want it to print the files if the string is found, I would also like it to print the file and path and string searched for in the files that were searched but not found. I’m a newbie, so please don’t be frustrated with the simplicity of the problem. I’m still learning. Thanks. Code below:

 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 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!!!"
  • 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:42:16+00:00Added an answer on May 23, 2026 at 8:42 am

    Folks, I think user706808 wants to search for all occurrences of searchstring in file and:

    • for each occurrence if string IS found in file, then on a per-LINE basis, print lineno, file pathname
    • if string is NOT found in file, then on a per-FILE basis print file pathname (but not the contents) and searchstring.
      Easiest way to do that is keep a boolean (or int) track of occurrences (nMatches), then print no-match-message at the end (if nMatches is 0 or False) before you close the file or the pathname goes out of context.

    Can you confirm? Assuming that’s what you want,
    all you need to change is to split up this megaline of code…

    for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
    

    into…

    for curPathname in walk_dir(directory, (".log", ".txt")):
        nOccurrences = 0
        for line in fileinput.input(curPathname):
            result = regex.search(whitespace.sub('', line))
            if result:
                ...
                nOccurrences += 1  # ignores multiple matches on same line 
            # You don't need an 'elif not result' line, since that should happen on a per-file basis
        # Only get here when we reach EOF
        if (nOccurrences == 0):
            NOW HERE print the "not found" message, for curPathname
        # else you could print "found %d occurrences of %s in ..."
    

    Sound good?

    By the way you can now simply refer to fileinput.filename() as ‘curPathname’.

    (Also you might like to abstract the functionality into a function find_occurrences(searchstring,pathname) which returns int or Boolean ‘nOccurrences’.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm obviously not quite getting the 'end-of-file' concept with C++ as the below program
This question relates to recursion. Consider the program shown below (not my real code,
I am getting access violation exceptions when running the code below when the CertFreeCertificateContext
Code below does not run correctly and throws InvalidOperationExcepiton . public void Foo() {
Code below is not working as expected to detect if it is in design
The code below shows a sample that I've used recently to explain the different
The code below gives me this mysterious error, and i cannot fathom it. I
The code below works. But if I comment out the line Dim objRequest As
The code below gives an error: Property 'Int32 Key' is not defined for type
The code below is the code i am using. It works fine in thunderbird

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.