#A file rain txt contains average

3 messages · Page 1 of 1 (latest)

round spire
#

Did you try asking ChatGPT for this?

I just had a quick conversation and got the following at the end of it.

def search_town(file_name, town_name):
    with open(file_name, 'r') as f:
        for line in f:
            if town_name in line:
                return line.split()[-1]
    return 'Town not found'

The prompts were:
For a data file (rain.txt) with a row format of "'Town Name' 'temp'" write a python function to search for a town.

It was close but wouldn't handle town names with spaces.

I don't think this will work for Towns with spaces in them. The line.strip().split() will break "New York" into "New" and "York".

This suggested a function that would work with csv files. I told it we didn't have that.

We don't have a csv file unfortunately. Could we search on the name being in a line and then split() and return the last element?

This is what gave me the snippet above.

#

As you can see, the snippet looks to do what you were asking. You just need to massage it for your specific need. e.g. output line rather than the temp.