简体   繁体   中英

Why does my function fail to create lists?

I am trying to create 5 lists out of 1 data file, the error I keep getting states that "airlines is not defined", yet it is the first thing I define in the function, how is this possible? What should I do to correctly create a list of airlines, arrival times, departure times, prices, and flight number?

USAir,1269,6:15,10:57,210
Delta,5138,16:20,22:10,212
UNITED,6001,14:12,20:50,217
Delta,5054,12:30,20:22,227
UNITED,5949,9:30,14:43,264
JetBlue,1075,17:00,20:06,280
Delta,1263,6:00,11:30,282
Delta,3824,9:00,14:45,282
USAir,1865,16:55,21:33,300
USAir,3289,18:55,23:41,300
USAir,1053,8:00,13:02,300
USAir,2689,12:55,18:09,300
USAir,3973,9:25,14:00,302
USAir,3267,11:30,16:13,302
USAir,3609,13:25,18:28,302
USAir,3863,15:35,20:54,302
USAir,3826,17:45,23:19,302
USAir,1927,7:00,12:53,302
Delta,3601,12:00,17:29,307
Delta,4268,7:15,12:46,307
UNITED,4676,6:00,10:45,321
UNITED,4103,11:00,16:16,321
USAir,3139,11:51,16:29,332
JetBlue,475,7:30,10:42,340
USAir,3267,11:30,18:15,367
UNITED,2869,16:55,21:33,406
UNITED,2865,6:15,10:57,406
UNITED,2729,8:00,13:02,406
UNITED,2645,7:00,12:53,445

and the code I am using is

def getFlights():

    airlines = []
    flightNums = []
    depTimes = []
    arriveTimes = []
    prices = []

    fname = input("Enter name of data file: ")
    infile = open(fname, 'r')

    line = infile.readline()
    line = line.strip()


    while line != "":
        line = line.strip()
        airline, flightNum, depTime, arriveTime, price = line.split(',')
        airlines.append(airline)
        flightNums.append(flightNum)
        depTimes.append(depTime)
        arriveTimes.append(arriveTime)
        prices.append(price)
        line = infile.readline()
        line = line.strip()

    infile.close()
    return airlines, flightNums, depTimes, arriveTimes, prices

getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)

Local variables inside a function are not accessible outside of the function call. If you want to use the returned values of getFlights you must assign them to variables in the calling context.

(airlines, flightNums, depTimes, arriveTimes, prices) = getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)

What b4hand has said is correct, however, the Pythonic way of doing this is using csv.reader and a with statement, eg:

import csv

filename = input('Enter filename: ')
with open(filename, 'rb') as fin:
    csvin = csv.reader(fin)
    airlines, flightNums, depTimes, arriveTimes, prices = zip(*csvin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM