Creation of empty csv

1

Hello

about 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, does anyone have an idea of the problem?

The original csv file I searched for is the following: link

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})
    
asked by anonymous 24.07.2017 / 17:32

1 answer

2

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

So just add the line arquivo.close() to 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, the word with in python. What this syntax does in the case of files is to execute the close() method on the object as soon as the code exits the indentation. In your case, it would look 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 reaches the end of the with block it will execute the output method, which for objects of type file (those created with open for example), such as variable / object arquivo , is the close() method. In this case, the with will be executed at the end of the indentation of arquivo.close() and the changes that resultado do are written to the disk (i.e. saved).

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

    
24.07.2017 / 20:46