Richard Rublev
Richard Rublev

Reputation: 8164

Print line numbers for lines containing a specific integer

I have tried this

import itertools
import numpy as np

with open('base.txt','r') as f:
    lst = map(int, itertools.imap(float, f))

num=1200

for line in lst:
    if num == line:
        print (line)

Just prints 1200...

I thought of re than

import re
import itertools

with open('base.txt','r') as f:
    lst = map(int, itertools.imap(float, f))

p = re.compile(r'(\d+)')

num=1200

for line in lst:
    if num in p.findall(line):
        print line

But I got

  File "a7.py", line 12, in <module>
    if num in p.findall(line) :
TypeError: expected string or buffer

What I want is the all line numbers that contain 1200.File has numerical inputs one by line,I have checked this.

Upvotes: 1

Views: 197

Answers (3)

Jacob Ritchie
Jacob Ritchie

Reputation: 1401

Staying as close to your proposed solution as possible, this should print out the line numbers for all lines containing your chosen num.

import itertools
with open('base.txt','r') as f:
    lst = map(int, itertools.imap(float, f))

num=1200

line_number = 1
for line in lst:
    if num == line:
        print (line_number)
    line_number += 1

Edit

However, your code just truncates the floats in your file - it will not round them correctly. 1200.9 becomes 1200 instead of 1201, for instance.

If this isn't a problem in your case, that is fine. However, in general it would be better to change your

lst = map(int, itertools.imap(float, f))

function call to something like

lst = map(int,map(round, itertools.imap(float, f)))

Upvotes: 2

zondo
zondo

Reputation: 20336

You can use enumerate():

with open('base.txt', 'r') as f:
    for i, line in enumerate(f):
        if num == int(line):
            print i

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191701

If you just want to print the line numbers, then you need to keep track of what line you are on.

Also, this code doesn't read the entire contents of the file into memory at once. (Useful for large files).

num = 1200

line_num = 0
with open('base.txt','r') as f:
    line_num += 1
    for line in f:
        if int(line) == num:
            print line_num

Upvotes: 1

Related Questions