Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search File And Find Exact Match And Print Line?

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.

like image 369
Robots Avatar asked Mar 30 '13 11:03

Robots


People also ask

How do you search for an exact word in Python?

import re with open('regex. txt', 'r') as a: word = "hello" for line in a: line = line. rstrip() if re.search(r"({})". format(word), line): print(f'{line} ->>>> match!


1 Answers

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.

like image 104
The Aelfinn Avatar answered Oct 05 '22 23:10

The Aelfinn