1

I need to do pretty much what a 'grep -i str file' gives back but I have been hitting my head up against this issue for ages.

I have a func called 'siteLookup' that I am passing two parameters: str 's', and file_handle 'f'. I want to a) determine if there is a (single) occurrence of the string (in this example site="XX001"), and b) if found, take the line it was found in, and return another field value that I extract from that [found] line back to the caller. (it is a 'csv' lookup). I have had this working periodically but then it will stop working and I cannot see why.

I have tried all of the different 'open' options including f.readlines etc.

#example line: 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'
#example from lookupFile.csv: "XX001","Charleston","United States"

sf = open('lookupFile.csv')

def siteLookup(s, f):
    site = s.split(',')[0].strip().upper()
    if len(site) == 5:
        f.seek(0)
        for line in f:
            if line.find(site)>=0:
                city = line.split(',')[1].strip('"').upper()
                return city
            # else site not found 
            return -1
    else:  # len(site) != 5
        return -1

city = siteLookup(line, sf)
print(city)
sf.close()

I am getting zero matches in this code. (I have simplified this example code to a single search). I am expecting to get back the name of the city that matches a 5 digit site code - the site code is the first field in the example "line".

Any assistance much appreciated.

1 Answer 1

1

Your return is wrongly indented - if the thing you look for is not found in the first line, it will return -1 and not look further.

Use with open(...) as f: to make your code more secure:

with open("lookupFile.csv","w") as f: f.write("""#example from lookupFile.csv: "XX001","Charleston","United States" """)

def siteLookup(s, f):
    site = s.split(',')[0].strip().upper()
    if len(site) == 5:
        f.seek(0)
        for line in f:
            if site in line:   # if site in line is easier for checking 
                city = line.split(',')[1].strip('"').upper()
                return city

        # wrongly indented - will return if site not in line
        # return -1

    # if too short or not found, return -1 - no need for 2 returns  
    return -1


line = 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'

with open('lookupFile.csv') as sf:
    city = siteLookup(line, sf)
    print(city)

Output:

CHARLESTON
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you - tested & confirmed as working as desired!

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.