Write to csv file

0

I have a function that returns a line and this must be inserted into a CSV file. The line has the following structure when returned by the function: ['x' - 'y', 'z', ['a', 'b', 'c', 'd', 'e', 'f']] .

When I try to insert, using the csv.writerow method, all characters are understood as a field. And that's not the behavior I need.

The above line for the purpose of the application should be inserted as follows: x - y , the first field; z , the second; and ['a', 'b', 'c', 'd', 'e', 'f'] , the third and last.

Has anyone had a similar situation that could help me?

What I tried to do:

Insertion code:

with open(arquivoSaida, 'at') as resultado:
    arqGravar = csv.writer(resultado)
    arqGravar.writerow(comparaNumeros(linhaAnterior, linhaPosterior))

Function that generates output to be inserted:

def comparaNumeros(linha, proxima):
    numerosRep = []
    totalRep = 0
    i = 1
    while i <= 15:
        j = 1
        while j <= 15:
            if linha[i] == proxima[j]:
                totalRep += 1
                numerosRep.append(linha[i])
                break
            else:
                j += 1
        i += 1
    csvLinha = linha[0] + " - " + proxima[0] + "," + str(totalRep) + "," + str(numerosRep)
    #print(csvLinha)
    return csvLinha
    
asked by anonymous 19.08.2018 / 19:29

1 answer

0

In the question, you mention that the function returns you:

['x' - 'y', 'z', ['a', 'b', 'c', 'd', 'e', 'f']]

But in the function you returned:

csvLinha = linha[0] + " - " + proxima[0] + "," + str(totalRep) + "," + str(numerosRep)

They are very different things. The first is a list, while the second is a string . Maybe what you wanted to do is:

csvLinha = [linha[0] + '-' + proxima[0], totalRep, numerosRep]

In this way, yes, what will be returned is as expected.

If you are using Python 3.6 or higher, the first value can be generated from a f-string :

csvLinha = [f'{linha[0]} - {proxima[0]}', totalRep, numerosRep]
    
19.08.2018 / 19:55