Problem inserting data into CSV file

Asked

Viewed 100 times

0

I am inserting the data into the file correctly, but when I open the file in Excel, the data is all in the same field in the table. Follows the code:

import csv

dados = open('DATA.csv','w')

try:
    writer = csv.writer(dados)
    writer.writerow(('Pais','Região','Status'))
    writer.writerow(('Brail','America do Sul','Emergente'))
    writer.writerow(('Argentina','Amerida do Sul','Subdesenvolvido'))
finally:
    dados.close()

print(open("DATA.csv","rt").read())

Soon after entering this data, I wanted to open in Excel, and appear a row with three fields containing Country, Region and Status, where in the case would be my table header, so below would have the values. Someone can tell me the problem ?

2 answers

0

Did you just want to present the data on the screen? Or do you want that after the execution of the code it opens the file with the data? If it is the first option, you can make the following changes to your code:

Use the with open to open csv and a loop for to print the data:

with open('\\DATA.csv', 'rt') as f:
try:
    csv.reader(f)
    for row in f:
        print(row)
except Exception as erro:
        print('erro: ', erro)

Always try to deal with possible exceptions, as it makes it easier when errors occur.

  • I want after the execution of the code, I open the CSV file in Excel and in each fields is the value I entered with write.

0

You need to set the delimiter to semicolon:

writer = csv.writer(dados, delimiter=';')

A tip: if you want to open the file in excel, why not generate a direct . xlsx file? Take a look at the libraries openpyxl and Xlsxwriter.

Browser other questions tagged

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