0

I have tried to create a python function which takes in 2 parameters; a file name and a search string. In this case the file name is the script itself (script.py) and the search string is 'name = "JOHN"'

#!/usr/local/bin/python2.7

import os, sys

#################
# Variable string
name = "JOHN"

#################
# Main function
def search_script_for_string(filename, searchString):

f = open(filename,'r') #open the given filename then
filedata = f.read()    #assign it to variable then
f.close()              #close the open filename

for lines in filedata:        #loop through each line in the filedata variable
    if searchString in lines: #if search string is found, then do all of this
        print ('Found string: %s') % searchString
        return True

    else:           #if not found, then do all of this
        print ('Did not find: %s') % searchString
        return False
        break

#################
# Pass the file name and the search string parameter to the function

search_script_for_string("test.py","name = \"" + name + "\"")

The problem is that it doesn't return expected results:

$ Did not find: name = "JOHN"

When it meant to say:

$ Found string: name = "JOHN"

If anyone can help correct my understanding of where I'm going wrong here, I'd be massively appreciative. Thanks

2 Answers 2

2

f.read() returns the entire contents of the file as a single string. You then iterate over those contents -- but iterating over a string yields only 1 character at a time so there is no way a character will contain the substring you are looking for.

def search_script_for_string(filename, searchString):
    with open(filename, 'r') as f:
        return searchString in f.read()

should do the trick. Alternatively, if you want to search line-by-line:

def search_script_for_string(filename, searchString):
    with open(filename, 'r') as f:
        for line in f:
            return searchString in line
Sign up to request clarification or add additional context in comments.

2 Comments

Note, I've used a context manager for managing the opening and closing of the file. You could continue to open and close the file as you have above, but the context manager is just a bit nicer IMHO :-)
Great response in a speedy 2 mins! Thank you.
0

You are iterating over each character of the file by calling for c in f.read().

Use for line in f and you will indeed iterate over each line.

Also prefer the use of with, this makes your code a lot more robust.

So this would be better:

with open('fileName') as f:
    for line in f:
        #process

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.