20

I searched around but i couldn't find any post to help me fix this problem, I found similar but i couldn't find any thing addressing this alone anyway.

Here's the the problem I have, I'm trying to have a python script search a text file, the text file has numbers in a list and every number corresponds to a line of text and if the raw_input match's the exact number in the text file it prints that whole line of text. so far It prints any line containing the the number.

Example of the problem, User types 20 then the output is every thing containing a 2 and a 0, so i get 220 foo 200 bar etc. How can i fix this so it just find "20"

here is the code i have

num = raw_input ("Type Number : ")
search = open("file.txt")
for line in search:
 if num in line:
  print line 

Thanks.

martineau
  • 119,623
  • 25
  • 170
  • 301
Robots
  • 201
  • 1
  • 2
  • 4
  • That somewhat depends on what the text in file.txt looks like. Can you give us some example lines? – naeg Mar 30 '13 at 11:41
  • Sorry The Text File Look Like This 1 blah 2 blah 3 blah 4 blah 5 blah going down in a list so there is a number before each line of text. – Robots Mar 30 '13 at 11:44

7 Answers7

28

Build lists of matched lines - several flavors:

def lines_that_equal(line_to_match, fp):
    return [line for line in fp if line == line_to_match]

def lines_that_contain(string, fp):
    return [line for line in fp if string in line]

def lines_that_start_with(string, fp):
    return [line for line in fp if line.startswith(string)]

def lines_that_end_with(string, fp):
    return [line for line in fp if line.endswith(string)]

Build generator of matched lines (memory efficient):

def generate_lines_that_equal(string, fp):
    for line in fp:
        if line == string:
            yield line

Print all matching lines (find all matches first, then print them):

with open("file.txt", "r") as fp:
    for line in lines_that_equal("my_string", fp):
        print line

Print all matching lines (print them lazily, as we find them)

with open("file.txt", "r") as fp:
    for line in generate_lines_that_equal("my_string", fp):
        print line

Generators (produced by yield) are your friends, especially with large files that don't fit into memory.

The Aelfinn
  • 13,649
  • 2
  • 54
  • 45
17

To check for an exact match you would use num == line. But line has an end-of-line character \n or \r\n which will not be in num since raw_input strips the trailing newline. So it may be convenient to remove all whitespace at the end of line with

line = line.rstrip()

with open("file.txt") as search:
    for line in search:
        line = line.rstrip()  # remove '\n' at end of line
        if num == line:
            print(line )
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
6

you should use regular expressions to find all you need:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

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

regular expression will return you all numbers in a line as a list, for example:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

lenik
  • 23,228
  • 4
  • 34
  • 43
1

It's very easy:

numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
   if numb == lines[0]:
      print lines
Oni1
  • 1,445
  • 2
  • 19
  • 39
1
num = raw_input ("Type Number : ")
search = open("file.txt","r")
for line in search.readlines():
    for digit in num:
        # Check if any of the digits provided by the user are in the line.
        if digit in line:
            print line
            continue
Jetlef
  • 139
  • 7
  • This Seems to still print everything in my .txt file containing any of numbers from Raw_input, any suggestion? – Robots Mar 30 '13 at 15:19
0

The check has to be like this:

if num == line.split()[0]:

If file.txt has a layout like this:

1 foo
20 bar
30 20

We split up "1 foo" into ['1', 'foo'] and just use the first item, which is the number.

naeg
  • 3,944
  • 3
  • 24
  • 29
-1

For example if you would like to show the line containing word "password" in it,

import re;
fpointer = open("access.log", "r");

for i in fpointer.readlines():
   line= re.findall(r'password', i);
   if line:
    print(i);
fpointer.close();
  • 1
    This is not a working solution for the current question. Also there is no need to use regular expressions in this example just `in` operator: `if 'password' in i:`. – Sergey Shubin Jun 04 '21 at 13:16