Generate Python CSV from txt

Asked

Viewed 255 times

0

I’m trying to run the code:

import csv

listaG = []
arquivoSaida = 'teste.csv'

with open('Arquivos_avanco.txt', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='-', quotechar='|')
    for row in spamreader:
        listaG.append([','.join(row)])
        #print (','.join(row))

with open(arquivoSaida, 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Marca', 'Modelo', 'Ano'])
    for i in listaG:
        spamwriter.writerow(i)

Error returned:

Traceback (Most recent call last): File "E: Johann Herbert Desktop python_test.py course", line 50, in spamwriter.writerow(['Brand', 'Model', 'Year'])

Typeerror: a bytes-like Object is required, not 'str'

I’m a beginner in language

  • And you do not need to open a file, read all the content in a list to then save it in another file; you can write as you read, in the same loop of repetition

1 answer

1


Fala Johann,

What is happening is the parameter you are putting in the CSV constructor.

with open(arquivoSaida, 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Marca', 'Modelo', 'Ano'])
    for i in listaG:
        spamwriter.writerow(i)

In the above section the wb means that you are writing to the file (w) and that you are writing to binary mode (b), so there is this recording error.

To save only the text just put only the 'w' in the same league and if you want to put in sequence, put the letter 'a' which will be referenced to append and will not overwrite previous information.

with open(arquivoSaida, 'w') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Marca', 'Modelo', 'Ano'])

Reference: CSV Python

Browser other questions tagged

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