-2

I have a list of integers, for example:

Mylist = [3, 6, 17, 55]

I have a Myfile.txt file containing 100s of lines.

Now I have to extract the lines which are present in Mylist from Myfile.txt and store them in another list.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

Here's a solution making use of list comprehension

with open('Myfile.txt','r') as f:
    data = f.read().split('\n')
NewList = [data[x] for x in Mylist]
clubby789
  • 2,543
  • 4
  • 16
  • 32
  • Downside of this is reading the whole file, even after the last line you actually want. Also you don't call the read method. – jonrsharpe Jan 23 '20 at 13:17
  • Correct, sorry, updated to fix calling the method. How would you suggest reading specific lines from a file? – clubby789 Jan 23 '20 at 13:20
  • 1
    Not specific lines, necessarily, but e.g. using `enumerate(f)` would give you an iterable of tuples `(index, line)` where you could consume only as many as you actually needed. There's an example of that on the dupe: https://stackoverflow.com/a/2081880/3001761 – jonrsharpe Jan 23 '20 at 13:25