Printing the lines that contain the substring 'snake' | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
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