Jake Miller
Jake Miller

Reputation: 25

How do I search a file line by line and then copy a line to a list if it contains a certain string?

I know how to read a whole file into a list line by line, but I cannot figure out the syntax for searching a file for a string and grabbing the whole line, and then appending that to a list.

Upvotes: 1

Views: 42

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114230

Simplest way I can think of:

with open('myfile.txt') as f:
    mylist = [line for line in f if search_string in line]

This will preserve the newlines at the end of every line since that's how iterating a file works. To remove the newlines, call line.rstrip('\n') before appending:

with open('myfile.txt') as f:
    mylist = [line.rstrip('\n') for line in f if search_string in line]

Other options are line.rstrip() to remove all trailing spaces including newlines, and line.strip() to remove all trailing and leading spaces, including of course the newline.

Upvotes: 1

ahota
ahota

Reputation: 449

The simplest way would be to use string.find() on each line as you parse the file: https://docs.python.org/3/library/stdtypes.html#str.find

For example:

with open('filename', 'r') as f:
  for line in f.readlines():
    if line.find('search_string') != -1:
      # do stuff

Upvotes: 0

Related Questions