Meatballjy
Meatballjy

Reputation: 1

Put specific lines into an array

I have a file which is like:

0.5 0.5 0.5 0.5

1 0.1

0.6 0.6 0.6 0.6

1 0.2

So my question is I just want the lines with "0.5" and "0.6" and put them in a array which would be like

0.5 0.5 0.5

0.6 0.6 0.6

How should I do this? I have tried several methods such as readlines and row.split, but I just cannot get the right form. Maybe I did not write the correct form of readlines and row.split.

Upvotes: 0

Views: 86

Answers (3)

user2555451
user2555451

Reputation:

This does it:

with open("/path/to/file") as f:
    print [l.strip() for l in f if " 0.5 " in l or " 0.6 " in l]

Output:

['0.5 0.5 0.5 0.5', '0.6 0.6 0.6 0.6']

Edit based off of comments:

Note that the above solution is for if the data is like that given. If it isn't, then you will need something a little more powerful:

from re import search
with open("/path/to/file") as f:
    print [l.strip() for l in f if search(r"\b0\.[56]\b", l)]

This will match for "0.5" or "0.6" anywhere in the string and will work for cases such as "0.5\n" and "0.6\n".

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

These solutions will check for 0.5 and 0.6 at any position in the line, not just at the start.

Using str.split:

with open('filename') as f:
    lis = []
    for line in f:
       spl = line.split()
       if '0.5' in spl or '0.6' in spl:
           lis.append(line.strip())

Using regex with word boundaries:

import re
with open('filename') as f:
    lis = []
    for line in f:
       if re.search(r'\b(0\.6|0\.5)\b', line):
           lis.append(line.strip())

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 82470

Well, you can do this by going over all the lines, and checking if the lines start with your desired variables, for your case (text.txt is the name of your presumed file):

with open('text.txt') as f:
    l = [var.rstrip() for var in f if var.startswith(('0.5','0.6'))]
    print(l)

Upvotes: 2

Related Questions