![]() |
search text file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: search text file (/thread-14350.html) |
search text file - jacklee26 - Nov-26-2018 I have one question with my code if I couldn't find match string it will keep print not find(if your text has 10 line, and could find your match, it will print 10 times). I wish if the string does not match just print one line not found. Example: enter your string: sss not found not found not found not found i wish to just print one line not find, how can i changed my code import sys substring = raw_input("enter your string : ") for line in open('POD.txt'): #if ("") in line: if substring in line: print (line) else: print ("not found") RE: search text file - ichabod801 - Nov-26-2018 Have a count variable, and increase it by one each time the line is found. After the loop, print not found if the count is zero. RE: search text file - jacklee26 - Nov-26-2018 i wish to occur like this: enter your string: sss not found do i have to put a if else statement inside the if loop RE: search text file - ichabod801 - Nov-26-2018 You need the if in the loop to check for matches, and add an increment to a count variable to it. You need to take the else out of the loop (unindent it), and convert it to an if count == 0:
RE: search text file - jacklee26 - Nov-27-2018 ok thanks if figure it out thanks. import sys substring = raw_input("enter your string : ") count =0 for line in open('POD.txt'): #if ("") in line: if substring in line: count +=1 print (line) if count==0: print ("string not found") But this only support python2, how to let python3 also support. if i run using python3 it will occur File "test_file.py", line 10 print (line) ^ TabError: inconsistent use of tabs and spaces in indentation RE: search text file - ichabod801 - Nov-27-2018 You need to make sure your indentation is consistent: either all spaces or all tabs. Try changing all tabs to four spaces or vice versa. Note that line 9 ( print(line) ) should be indented one more level to be even with count += 1.
|