Creation of empty csv

Asked

Viewed 184 times

1

hello

on the python code below, I want to create a csv with the sum of inhabitants in each state

but it creates an empty csv file

please, someone has idea of the problem?

the original csv file in which I searched the data is this: https://drive.google.com/open?id=0B72DpG1W01nneHU5UXh0TzdSSVU

code:

import csv

brasil = csv.DictReader(open('municipios-brasil.csv', encoding='utf-8'))

total = {}

for municipio in brasil:
    estado = municipio['estado']
    habitantes = int(municipio['habitantes'])

    if estado not in total:
        total[estado] = 0

    total[estado] = total[estado] + habitantes

arquivo = open('habitantes.csv', mode = 'w', encoding = 'utf-8')

resultado = csv.DictWriter(arquivo, fieldnames = ['estado', 'habitantes'])

resultado.writeheader()

for estado, habitantes in total.items():
    resultado.writerow({'estado': estado, 'habitantes':habitantes})

1 answer

2


If you run your code from in REPL (IDLE, ipython, or python itself) the file will not close and the changes will not be 'flushed' (written) to the file.

So just add the line arquivo.close() at the end of your script and the changes will be written to your file.

One way to prevent this from happening is to use context managers, commonly the word with python. What this syntax does in the case of files is to execute the method close() on the object as soon as the code leaves the indentation. In your case, it would be something like this:

import csv

brasil = csv.DictReader(open('municipios-brasil.csv', encoding='utf-8'))

total = {}

for municipio in brasil:
    estado = municipio['estado']
    habitantes = int(municipio['habitantes'])

    if estado not in total:
        total[estado] = 0

    total[estado] = total[estado] + habitantes

with open('habitantes.csv', mode = 'w', encoding = 'utf-8') as arquivo:

    resultado = csv.DictWriter(arquivo, fieldnames = ['estado', 'habitantes'])

    resultado.writeheader()

    for estado, habitantes in total.items():
        resultado.writerow({'estado': estado, 'habitantes':habitantes})'

As soon as the interpreter arrives at the end of the block with it will execute the output method, which for objects of type file (those created with the open for example), as the variable/object arquivo, is the method close(). In this case, when arriving at the end of the indentation of the with will be executed arquivo.close() and the amendments resultado makes are written to disk (i.e. saved).

You can read about the syntax of with here, but I find the documentation a little cryptic.

  • Thank you very much!

  • @Reinaldochaves, consider marking my answer as accepted, so the staff can find it and review

  • Sure, it worked. But I don’t know where to take the answers

  • It’s a tick under the voting box ^_^

Browser other questions tagged

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