Search code examples
pythonstringlistfor-loopurlopen

open file with string that has multiple variables


I can get the text file when I set airport to one variable. However, how can I get the text files for multiple airport codes and display the information?

airport = 'KSFO, KSJC, KOAK'

for metar in urlopen('http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT' %airport):
        metar = metar.decode("utf-8")
        if "%s" %airport in metar:
            print metar

Solution

  • If your goal is to fetch the weather observations for each of those airports, you could use:

    from urllib import urlopen
    airports = 'KSFO, KSJC, KOAK'
    
    for airport_code in airports.split(","):
        for metar in urlopen('http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT' % airport_code.strip()):
            metar = metar.decode("utf-8")
            print metar
    

    For me, the output is:

    2012/10/30 07:56 KSFO 300756Z 29005KT 10SM FEW001 13/11 A3006 RMK AO2 SLP178 T01280111 402110117

    2012/10/30 07:53 KSJC 300753Z AUTO 00000KT 10SM CLR 10/ A3005 RMK AO2 SLP175 T0100 402060089 $

    2012/10/30 08:14 KOAK 300814Z 06003KT 10SM OVC004 13/12 A3007 RMK AO2