Create table csv in python

Asked

Viewed 2,116 times

1

I’m trying to build a table from information collected on a website.

The problem is that although the print comes out as expected, at the time of saving in csv file is going only the last record.

Below the code snippet that’s giving me a headache.

titulo = 0
atributo = 1
alinhado = ""

with open(arquivoOutput, 'w') as csvfile:
    escrevelinha = csv.writer(csvfile, delimiter=';', quoting=csv.QUOTE_MINIMAL)
    escrevelinha.writerow(["Matricula","Servidor","Cargo","Referência","Remuneração","Abono","Eventuais", "Descontos", "Salario Liquido"])


    while (titulo < 18):
        apenastag1 = str(apenastag.find_all("td")[titulo].get_text())
        apenastag2 = str(apenastag.find_all("td")[atributo].get_text())
        #print(apenastag2)
        alinhado = alinhado + apenastag2 + ";"

        titulo = titulo + 2
        atributo = atributo + 2

    alinhado = alinhado + "\n"
    print(alinhado)
    escrevelinha.writerow([alinhado])

The print output is as follows:

Saída print

The print is going exactly as expected.

Already the CSV file has only the last record.

inserir a descrição da imagem aqui

How do I fix this?

  • Have you tried using the write() instead of writerow()?

3 answers

2

Move that line:

escrevelinha.writerow([alinhado])

Which is outside the while, into the same, so every interaction and search of the element , already being made the recording in csv.

  • There is the possibility to save this string with a single writerows?

  • 1

    Yes, it is. the writerows takes an iterable as an argument to be written, with that you create a list ( as an example of eternal ) where each item of it will be a line. With this inside the whilte vc will creating the elements and inserting inside this list, and outside the for uses the writerows to be written.

  • 1

    Thank you for your attention.

0

Would changing the parameter "w" by "a" be better? Because w (write) overwrites what has already been stored while a (append) adds one more item to "list".

0

Or do so using ILDE-Python in the specialized CSV Nosql database called CSV Comp DB:

import cql_to_python
db ="path\\dbfolder\\"
table = "Mytable"
cql = str("")
cql = create_table(db,table) #cria tablea csv
cql = cql + create_fields(db,table,"(ID ; FIELD1 ; FIELD2)") #cria campos
cql = cql + add_data(db,table,"(0001 ; DATA1 ; DATA2)") #add dados
CSV_COMP_DB_execute(cql) #executa o banco de dados

Browser other questions tagged

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