Reading of csv with Django

Asked

Viewed 188 times

3

Well, I’m working with an open database, and it’s in CSV, I’m using DJANGO to read the CSV and so entering into the database... However is giving a flaw in the insertion of the first year,I’m trying to insert 8 years of data, the first year it inserts only 11 months, so is missing enter 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

Thus reading each column of csv and changing the columns automatically and changing the year, as each column is one month. Does anyone know why I’m not getting the insertion right?

1 answer

3


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

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

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

Alternatively, you can take the test before upgrading coluna, and not after:

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 the print, that I imagine to be there just for debugging, right? ). Personally, I think in the second form the logic becomes clearer.

  • 1

    Solved friend, the second way worked also... I resolved also doing if coluna%12 == 1:&#xA; print ano&#xA; mes = 1&#xA; ano = ano + 1 This print is just to debug even...but it worked 100%!! Thank you!

  • @Marcelohenriquecasali if the answer really helped/solved should accept it, below the down arrow to the left of the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.