Pattern in a file

Lucaci Andrew 0 Tallied Votes 318 Views Share

Inspired by some C and C++ threads regarding finding a specific pattern in a file.

def find():
    a = raw_input("Insert file: ")
    b = raw_input("Insert pattern: ")
    try:
        found = 0
        for i in open(a, 'r'):
            if b in i:
                found = 1
        if found == 1: print "Patter was found."
        else: print "Pattern not found."
    except:
        print "Invalid file."
find()
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

More general snippet on the same subject can be found at scan filetree for files containing text

snippsat 661 Master Poster

a,b are are really bad variable names.
It`s ok to use only in small code examples,should not be used in finish scripts.
if b in i really easy to understand?
Bare except: should not be used.
I explain better why not in this post.
http://www.daniweb.com/software-development/python/threads/423971/python-program-detect-if-files-exist#post1812471
There is no need to use found 0 and 1.

So a more pythonic version would look like this.

def find():
    file_in = raw_input("Insert file: ")
    pattern = raw_input("Insert pattern: ")
    try:
        with open(file_in) as a_file:
            for file_content in a_file:
                if pattern in file_content:
                    return 'Pattern was found'
                return 'Pattern was not found'
    except IOError:
        return "Invalid file."

print find()
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Ok, for me something like this would go (but preferably I would invoke fileselection dialog to choose file)

import os

def read_valid(case_insensitive=True):
    while True:
        try:
            file_in = raw_input("Give valid file name: ")
            with open(file_in) as infile:
                return infile.read().lower() if case_insensitive else infile.read()
        except IOError:
            print "Invalid file.\nFiles in current directory are:\n\t%s" % '\n\t'.join(os.listdir('.'))

def find(pattern, case_insensitive=True):
    if case_insensitive:
        pattern = pattern.lower()
    return 'Pattern was %sfound.' % ('' if pattern in read_valid(case_insensitive) else 'not ')


print find(raw_input("Pattern to find: "))
Lucaci Andrew 140 Za s|n
def find():
    file = raw_input("Insert file: ")
    pattern = raw_input("Insert pattern: ")
    try:
        if any(iter for iter in open(file, 'r') if pattern in iter): print "Patter was found."
        else: print "Pattern was not found."
    except:
        print "Invalid file."
find()

As pyTony suggested for an inline-searching.

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

iter is built in function, so use other variable name to avoid confusion.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.