Kevin R.
Kevin R.

Reputation: 602

Checking to see if a specific string is in a file txt

I'm trying to check if a specific string is in a file text

so i have this file that contains the following:

Active Internet connections
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)        rxbytes    txbytes
tcp4       0      0  192.168.1.6.50860      72.21.91.29.http       CLOSE_WAIT         892        691
tcp4       0      0  192.168.1.6.50858      www.v.dropbox.co.https ESTABLISHED      27671       7563
tcp4       0      0  192.168.1.6.50857      162.125.17.1.https     ESTABLISHED      17581       3642

and here is my code:

char = ""
file = open("location")

for  i, line in enumerate(file):
        addi = i + 1
        if line.strip() == char:
                print "MATCH FOUND on line " + str(addi)

print "finished"

For this to work, I have to paste the entire line in my char var. For example, it works if I paste "Active Internet connections", but If I put "Internet", it goes straight to the print "finished" line. How would I fix this?

Upvotes: 0

Views: 74

Answers (7)

Cosinux
Cosinux

Reputation: 321

Try this:

search = "what you want to find goes here"
filename = "file to read"
with open(filename) as f:
    for i, line in enumerate(f, 1):
        if search in line:
            print "MATCH FOUND in line", i

Upvotes: 1

Filippo Costa
Filippo Costa

Reputation: 498

Looking for a sub-string in Python is very simple task. Python's methods find() and count() are very useful in this context.

# This is the string you're looking for
ip = "192.168.1.6.50860"

# You need to do both, open and read file, to get its content
file = open("/home/my/own/directory/here/file.txt").read()

def findLine(text, string):
    if string in text:
        return "MATCH FOUND on line {}".format(text[0, text.find(string)].count("\n") + 1)
    else:
        return "MATCH NOT FOUND"

print(findLine(file, ip)) # Prints 3 (1-based indexing)

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191701

Might want to try using with open() as for proper file-handling.

And using the in keyword will work better than == because you want a match if it contains your string.

Also, using str.format is more readable IMO than "stuff" + str(value)

find = "Active Internet connections"
with open('location') as f:
    for i, line in enumerate(f, 1):
        if find in line:
            print("Match found on line {}".format(i))

print("finished")

Upvotes: 2

inblank
inblank

Reputation: 416

You are checking if the line is in char, but you should do the reverse, since the entire line isn't in the char:

for  i, line in enumerate(file):
        line_index = i + 1
        if char in line:
                print "MATCH FOUND on line " + str(line_index)

print "finished"

also, I would recommend not to use char as a variable name. try to use more explicit and less ambiguous names like pattern_to_find

Upvotes: 1

Amit Gold
Amit Gold

Reputation: 767

As simple as char in line.

Example usage is that "hi" in "hit" will be True, and "hi" in "hello" will be False.

Upvotes: 1

AChampion
AChampion

Reputation: 30258

You need to look for contains (in) rather than equals (==). You can also use a list comprehension to get all the matches then print out the results:

char = "<search-string>"
with open("location") as file:
    results = [i for i, line in enumerate(file, 1) if char in line]

if results:
    print "MATCHES FOUND on lines " + ', '.join(results)

print "finished"

If you need more complicated search rules, then you may want to look at the regex module re

Upvotes: 2

Nick Burns
Nick Burns

Reputation: 192

In Python, strings are nothing more than lists of characters. To check if a string exists in another, you can use the in operator.

if char in line:
    # do something

Upvotes: 1

Related Questions