Write to csv file

Asked

Viewed 242 times

0

I have a function that returns a line and this should be inserted in 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 insertion, using the method csv.writerow, all characters are understood as a field. And that’s not the behavior I need.

The above row 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.

Some fellow went through similar situation that could help me?

What I tried to do:

Code for insertion:

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

Function generating the 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
  • What language? Could you put your code in the question?

  • The language is python.

1 answer

0


In the question, you quote 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)

These 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 follows 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]
  • I will correct and return the result.

  • Dear Anderson, corrected yes. With a small adjustment in the first field. Your answer was in line[0] - next[0]; the change was in line[0] + "-" + next[0]. I’m a beginner in python, so I’ll go into intricate detail with the language. But I’ll learn. Thank you very much for the prompt response. Now I’m gonna fix the recording code.

Browser other questions tagged

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