suncup224
suncup224

Reputation: 123

KML to CSV: a bytes-like object is required, not 'str'

I am using the following code to convert a KML file into a CSV file, based on what is provided in this link: https://gist.github.com/mciantyre/32ff2c2d5cd9515c1ee7

The code I used is as follows (essentially what is in the link)

from bs4 import BeautifulSoup
import csv


def process_coordinate_string(str):
    """
    Take the coordinate string from the KML file, and break it up into [Lat,Lon,Lat,Lon...] for a CSV row
    """
    space_splits = str.split(" ")
    ret = []
    # There was a space in between <coordinates>" "-80.123...... hence the [1:]
    for split in space_splits[1:]:
        comma_split = split.split(',')
        ret.append(comma_split[1])    # lat
        ret.append(comma_split[0])    # lng
    return ret

def open_the_file():
    """
    Open the KML. Read the KML. Open a CSV file. Process a coordinate string to be a CSV row.
    """
    with open('blah.kml', 'r') as f:
        s = BeautifulSoup(f, 'lxml')
        with open('out.csv', 'wb') as csvfile:
            writer = csv.writer(csvfile)
            for coords in s.find_all('coordinates'):
                writer.writerow(process_coordinate_string(coords.string))

open_the_file()

However, this throws an error: TypeError: a bytes-like object is required, not 'str'. The error is attributed to the second last line (writer.writerow....).

How can this issue be resolved? I am using python 3.6.2.

Upvotes: 0

Views: 690

Answers (1)

Rohit Jindal
Rohit Jindal

Reputation: 211

You need to convert the string to the byte object before you write, as you have opened the csvfile in the binary mode ie. 'wb'

Use the below line

writer.writerow(process_coordinate_string(coords.string).encode('utf-8'))

Upvotes: 1

Related Questions