Reading csv with django

2

Well, I'm working with an open database, and it's in CSV, I'm using DJANGO to read the CSV and thus inserting into the database ... But it's failing to insert the first year, I'm trying to insert 8 years of data, the first year it inserts only 11 months, so it's missing insert 1 month to properly close the data.

from django.shortcuts import render
from models import Internacao
import csv


def csvInternacao(request):
        coluna = 1
        mes = 1
        ano = 2008
        while (ano < 2017):
            with open('locale', 'rb') as csvfile:
                spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
                for row in spamreader:
                    if row[0] is not None:
                        t = Internacao()
                        t.idmunicipios = row[0]
                        t.quantidade = row[coluna]
                        t.data = str(ano) + '-' + str(mes) + '-01'
                        t.save(force_insert=True)
                        print t.idmunicipios, t.data, t.quantidade
            mes = mes + 1
            coluna = coluna + 1
            print mes
            if coluna%12 == 0:
                print ano
                mes = 1
                ano = ano + 1

So by reading each column of the csv and changing the columns automatically and changing the year, because each column is a month. Does anyone know why I can not do the insert correctly?

    
asked by anonymous 01.09.2016 / 00:43

1 answer

3

If your columns are based on 1 , then your smallest [valid] value will be 1 and its largest value will be 12 . This means that you should only reset the month when the value does not become valid - that is, 13 .

In the second iteration, the column will start with 12 + 1 = 13 and end with 12 + 12 = 24 , so you will reset when it reaches 12 + 13 = 25 . That is, it is not when coluna%12 is zero that you have to reset, but in the following index to it:

if (coluna-1)%12 == 0:
    print ano
    mes = 1
    ano = ano + 1

Alternatively, you can test before updating coluna , not later:

if coluna%12 == 0:
    print ano
    mes = 1
    ano = ano + 1
else:
    mes = mes + 1
    print mes

coluna = coluna + 1

The result will be the same (except for print , which I imagine is only there for debugging, right?). Personally, I think the second way the logic gets clearer.

    
01.09.2016 / 01:05