0

Printing the lines that contain the substring 'snake'

  #opening the text file f= open("Acrochordidae.txt", "r")   for data in f:     lines= f.readlines()     if lines == "snake":         newline= f.readline()     else:         break           print(newline) I tried to format it in different ways but this is how far I got.

5th May 2019, 11:03 PM
Kittyky.n
Kittyky.n - avatar
8 odpowiedzi
0
lines = open('yourfile.txt', 'r').readlines() matches = [line for line in lines if line.lower().find('snake') != -1] print(matches)
6th May 2019, 4:38 AM
Dlite
Dlite - avatar
6th May 2019, 4:25 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 2
for data in f will give you the lines in f, no need to use lines= f.readlines(), especially not in the for loop if lines == "snake" will check if the whole line equals "snake", not if "snake" is somewhere in the line (use if substring in string) newline= f.readline() doesn't make sense else: break will break the whole for loop as soon as "snake" is not in a line
6th May 2019, 4:40 AM
Anna
Anna - avatar
+ 1
So you want to 1.Open a file 2.Print out lines that contain "snake" right
6th May 2019, 4:13 AM
Dlite
Dlite - avatar
+ 1
And I'm sorry if my code didn't make sense. I'm still trying to understand file handling. I will try to get better.
6th May 2019, 4:50 AM
Kittyky.n
Kittyky.n - avatar
0
yes
6th May 2019, 4:28 AM
Kittyky.n
Kittyky.n - avatar
0
I just need understanding how to format it right. Like finding the substring.
6th May 2019, 4:30 AM
Kittyky.n
Kittyky.n - avatar
0
Thank you. I will try if it works.
6th May 2019, 4:48 AM
Kittyky.n
Kittyky.n - avatar