Darwin Tech
Darwin Tech

Reputation: 18929

csv reader failing on new line without delimiter

I am building an application which accepts csv data as an uploaded file.

Here is the relevent part of my view:

def climate_upload(request):
    ...
    reader = csv.reader(file, delimiter=';')    # news csv reader instance 
    next(reader)    # skip header row

    for line in reader:
        if not line:
            continue    
        report = site_name
        report.year = line[1]
        report.month = line[2]
        ...
        report.save()
    file.close()    # close file
    ...

So, this works fine on data which looks like this:

;"headers"
;2012;5;2012-06-01;27.1;24.5;29.8;26.8;85;0.8
;2012;5;2012-06-02;27.1;24.5;29.8;26.8;85;0.8

But fails on this:

"headers"
2012;5;2012-06-01;27.1;24.5;29.8;26.8;85;0.8
2012;5;2012-06-02;27.1;24.5;29.8;26.8;85;0.8

Note the lack of initial delimiter on each line.

Unfortunately MS Excel seems to spit out the second version. I assume that reader is not recognizing a new line as a delimiter. Is there some flag with reader which will force it to accept \n as a delimiter as well as ; ?

Any help much appreciated.

Upvotes: 1

Views: 262

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336258

The delimiters or newlines aren't the problem - you're counting incorrectly.

The first element of a list has the index 0. So it should be

report.year = line[0]
report.month = line[1]
# etc.

I'm guessing you're running into a List index out of range exception on the last element (line[9]).

Upvotes: 2

Related Questions