Problems copying data to csv file (to bytes-like object is required, not 'str')

2

I'm having trouble copying a column of data into a csv file.

The original csv file looks something like this:

ID;texto
1;El niño juega
2;La rana salta
3;Mi código no funciona

The code I use reads data from a csv file, and generates a list. Then I try to paste that list into another CSV. I do the following:

import csv
with open("scraped.csv", "r", encoding="utf8") as csvfile:
    reader = csv.DictReader(csvfile, dialect='unix', delimiter = ",")
    sent =[]
    for row in reader:
        sent.append(row["texto"])
with open("results.csv", 'wb') as csvfile:
    writer = csv.writer(csvfile, dialect='unix', delimiter=",",
                        quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['texto'])
    writer.writerow([sent])

I get the following error: Traceback (most recent call last):   File "C: / Users / Testing 2.py", line 46, in     writer.writerow (['text']) TypeError: a bytes-like object is required, not 'str'

The objective is to be able to copy each phrase in a row in the new csv file, under the text title.

Thanks for the suggestions

    
asked by pyring 04.11.2017 в 19:30
source

1 answer

5

You are trying to save text (encoded string) in a binary file ( wb ). writer.writerow wait for a text string (which is what you pass) not bytes, simply open the text file in text mode ( 'w' instead of 'wb' ):

import csv

with open("Libro.csv", "r", encoding="utf8") as csvfile:
    with open("results.csv", 'w', encoding="utf8") as csv_out:
        reader = csv.DictReader(csvfile, dialect='unix', delimiter = ",")
        writer  = csv.writer(csv_out, dialect='unix', delimiter=",",
                             quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(["texto"])
        for row in reader:
            writer.writerow([row["texto"]])

Edit:

If you want to use the list as you do in your code, just click on it:

for item in sent:
    writer.writerow([item])

Or use writer.writerows and a generator:

import csv

with open("Libro.csv", "r", encoding="utf8") as csvfile:
    reader = csv.DictReader(csvfile, dialect='unix', delimiter = ",")
    sent =[]
    for row in reader:
        sent.append(row["texto"])

with open("results.csv", 'w') as csvfile:
    writer = csv.writer(csvfile, dialect='unix', delimiter=",",
                        quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['texto'])
    writer.writerows([row] for row in sent)
    
answered by 04.11.2017 / 19:52
source