Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need do to print all that lines in which python appears using find() command in a file. Using python.
Python
fhand=open('demo.txt')                           
for line in fhand:
        line=line.rstrip()
        if(line.find('python')):
           continue
        print(line)

these are my file content
python is fun
python java 
sai python
sachin
ganesha


currently its printing first 2 lines only

What I have tried:

Python
fhand=open('demo.txt')
for line in fhand:
        line=line.rstrip()
        if(line.find('python')):
           continue
        print(line)
this is my code please help me
Posted
Updated 4-Jul-18 1:30am
v2

Python
fhand=open('demo.txt')
for line in fhand:
  line=line.rstrip()
  if( line.find('python') != -1):
    print(line)
 
Share this answer
 
Comments
Richard MacCutchan 4-Jul-18 8:14am    
+5, now we are equal.
The find method returns the index to the first occurrence of the find target. You are only printing the ones where the index is zero. Change your loop to:
Python
for line in fhand:
  line=line.rstrip()
  if(line.find('python') != -1):
    print(line)


In future please format your code properly between <pre lang="Python"></pre> tags, as I have done here. It makes it more readable.
 
Share this answer
 
Comments
CPallini 4-Jul-18 7:47am    
Wow, great minds think alike :-D
5.
Richard MacCutchan 4-Jul-18 8:14am    
Yes, but you got there before me.
Python
if(line.find('python')):
  continue

Python String find() Method[^]
According to the documentation find() returns -1 for 'not-found' and index (0 based) for 'found'... However 'if' is about ture/false, where any number except 0 is true...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900