How to search for a string in text files?

后端 未结 12 2272
死守一世寂寞
死守一世寂寞 2020-11-22 04:29

I want to check if a string is in a text file. If it is, do X. If it\'s not, do Y. However, this code always returns True for some reason. Can anyone see what i

相关标签:
12条回答
  • 2020-11-22 05:23

    Your check function should return the found boolean and use that to determine what to print.

    def check():
            datafile = file('example.txt')
            found = False
            for line in datafile:
                if blabla in line:
                    found = True
                    break
    
            return found
    
    found = check()
    if found:
        print "true"
    else:
        print "false"
    

    the second block could also be condensed to:

    if check():
        print "true"
    else:
        print "false"
    
    0 讨论(0)
  • 2020-11-22 05:23

    If user wants to search for the word in given text file.

     fopen = open('logfile.txt',mode='r+')
    
      fread = fopen.readlines()
    
      x = input("Enter the search string: ")
    
      for line in fread:
    
          if x in line:
    
              print(line)
    
    0 讨论(0)
  • 2020-11-22 05:24

    I made a little function for this purpose. It searches for a word in the input file and then adds it to the output file.

    def searcher(outf, inf, string):
        with open(outf, 'a') as f1:
            if string in open(inf).read():
                f1.write(string)
    
    • outf is the output file
    • inf is the input file
    • string is of course, the desired string that you wish to find and add to outf.
    0 讨论(0)
  • 2020-11-22 05:33
    if True:
        print "true"
    

    This always happens because True is always True.

    You want something like this:

    if check():
        print "true"
    else:
        print "false"
    

    Good luck!

    0 讨论(0)
  • 2020-11-22 05:34

    As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:

    def check():
        with open('example.txt') as f:
            datafile = f.readlines()
        found = False  # This isn't really necessary
        for line in datafile:
            if blabla in line:
                # found = True # Not necessary
                return True
        return False  # Because you finished the search without finding
    

    Then you can test the output of check():

    if check():
        print('True')
    else:
        print('False')
    
    0 讨论(0)
  • 2020-11-22 05:34
    found = False
    def check():
    datafile = file('example.txt')
    for line in datafile:
        if "blabla" in line:
            found = True
            break
    return found
    
    if check():
        print "found"
    else:
        print "not found"
    
    0 讨论(0)
提交回复
热议问题