python-3.x - KML 到 CSV:需要一个类似字节的对象,而不是“str”
问题描述
根据此链接中提供的内容,我正在使用以下代码将 KML 文件转换为 CSV 文件:https ://gist.github.com/mciantyre/32ff2c2d5cd9515c1ee7
我使用的代码如下(基本上是链接中的内容)
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()
但是,这会引发错误:TypeError: a bytes-like object is required, not 'str'。该错误归因于倒数第二行(writer.writerow ....)。
如何解决这个问题?我正在使用 python 3.6.2。
解决方案
您需要在写入之前将字符串转换为字节对象,因为您已经以二进制模式打开了 csvfile,即。'wb'
使用下面的行
writer.writerow(process_coordinate_string(coords.string) .encode('utf-8') )