2

I'm trying to read a csv file, and create a 2 dimensional list from the values stored inside.

However I'm running into trouble when I try to check whether or not the values stored can be converted into floats.

Here is the function I have written, which reads the file and creates a list.

def readfile(amount, name):
    tempfile = open(name).readlines()[1:]    #First value in line is never a float, hence the [1:]
    rain_list = []
    count = 0.0
    for line in tempfile:            
        line = line.rstrip()
        part = line.split(",")
        try:
            part = float(part)
        except ValueError:
            print("ERROR: invalid float in line: {}".format(line))
        rain_list.append(part[amount])
        count += 1
    if count == 0:
         print("ERROR in reading the file.")
    tempfile.close()
    return rain_list

It might be a little messy, since it's essentially a patchwork of different possible solutions I have tried.

The values it gets are the name of the file (name) and the amount of values it reads from the file (amount).

Has anyone got an idea why this does not work as I expect it to work?

1 Answer 1

2

part is a list of strings. To check & convert for all floats, you'd have to do:

part = [float(x) for x in part]

(wrapped in your exception block)

BTW you should use the csv module to read comma-separated files. It's built-in. Also using enumerate would allow to be able to print the line where the error occurs, not only the data:

reader = csv.reader(tempfile)  # better: pass directly the file handle
# and use next(reader) to discard the title line
for lineno,line in enumerate(reader,2):  # lineno starts at 2 because of title line
    try:
        line = [float(x) for x in line]
    except ValueError:
        print("ERROR: invalid float in line {}: {}".format(lineno,line))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I haven't got any experience with the csv module yet, I'll have to check it out. When you say wrapped in your exception block, what do you mean by that?
I mean: like you did before. I have added a code snippet which uses csv

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.