I have a function that reads in a data file and returns the values in that file as a list printing comments.

def loadcsv(filename):
    """Loads a comma-separated-value file (.csv) and returns a list of all the   numerical values, ignoring comments and any malformatted data."""
    """Function should ignore bad data, but print all comments."""
    datafile = open(filename)
    global datafile
    numbers = []
    for line in datafile:
    if line[0] == "#":
        print line
    elif line[0] != "#" or type(line[0]) != type(0) or type(line[0]) != type(0):
        print "Bad Data"
    else:
        numbers.append(line)
    datafile.close()
    return numbers

Not sure how I get the error given my declaration of datafile as global.

有帮助吗?

解决方案

The global statement needs to be the first line in your function, so just swap the global datafile and datafile = open(filename) lines.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top