user1841859
user1841859

Reputation: 155

Print lines with a given value

I am trying to run some simple code in python to read a text file and print only lines with a certain value in the last column.

This is the text file:

234 324 4
124 35 5
13 434 7
34 465 1
41 46 2 
25 62 2

and my attempted code is

data = np.loadtxt('SelectValueTest.txt')

line = range (0,5)
for line in data:
    for n in data[:,2]:
        if n ==1:
            print line 

I know that I need to change the print line bit as this is just printing every line if any of them include to value 1, but I'm not sure what to put?

Sorry for the really basic question! I'm just starting out and struggling to get the hang of it!

Upvotes: 1

Views: 124

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213271

Just split each line on space, and check whether the last element of the list obtained is equal to the required value or not: -

with open('SelectValueTest.txt', 'rb') as data:
    for line in data:
        if line.strip().split(" ")[-1] == '1':
             print line 

Upvotes: 3

MikeHunter
MikeHunter

Reputation: 4304

with open('SelectValueTest.txt', 'rb') as f:
    for line in f:
        if line.strip().endswith('1'):
            print line

That will print out all lines ending with 1. You need the strip() to remove the newlines etc at the end of the lines. This will work with the data you showed us. However, if you have values with 2 or more digits at the end of the lines, then Rohit's method is what you will need to use.

Mike

Upvotes: 2

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

So, what is happening is you are printing any line that contains a 1 in it, anywhere.

A better solution would be to read it with cvs reader, like this:

with open(file, 'rb') as csvfile:
    data= csv.reader(csvfile, delimiter=' ')
    for line in data:
        if line[-1] ==1:
            print line 

Upvotes: 0

Related Questions