OrdinaryProgrammer
OrdinaryProgrammer

Reputation: 223

Getting specific lines in a text file and pass it to an array

Not sure if this has been asked. But here it goes.

Let's say I have a text file containing

1 Why
2 We
3 Please
4 OR
5 I
6 AM
7 HUMAN
8 OR
9 MY
10 time
11 to
12 eat

Now I want to get lines 5-7 and 9-12 then put it in an array. Do note that the OR word acts like a delimiter in the text file.

I know the usual way of reading a text file in python is using a for loop, but I cant think of a way to do this by using a for loop or any other methods.

Upvotes: 1

Views: 85

Answers (2)

Alekhya Vemavarapu
Alekhya Vemavarapu

Reputation: 1155

import csv;  
import re;  
crs = csv.reader(open("D:/a.txt", "r"));  
line = ""  
for each in crs:  
    line = line + each[0];  

print re.split('OR',line)  

Answer:

['WhyWePlease', 'IAMHUMAN', 'ME']

Upvotes: 0

shreyas
shreyas

Reputation: 2620

You can do

data = open(<textfile>).read()
segments = data.split('OR')

and then split the segments by \n to get lines in that segment

lines = [seg.split("\n") for seg in segments]

Upvotes: 3

Related Questions