2

How to convert kml to shapefile using python code? I'm using the code below but it's not properly coverting:

vlayer = QgsVectorLayer("D:\KML-Images\dp0844061p.kml", "line", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
QgsMapLayerRegistry.instance().removeMapLayer(vlayer)

_writer = QgsVectorFileWriter.writeAsVectorFormat\
(_vlayer,"hoppla.shp","utf-8",None,"ESRI Shapefile")

_writer = QgsVectorFileWriter.writeAsVectorFormat(vlayer,r"D:\KML-Images\dp0844061p.shp","utf-8",None,"ESRI Shapefile")

_writer = QgsVectorFileWriter.writeAsVectorFormat(vlayer,r"D:\KML-Images\ShapeFile\dp0844061p.shp","utf-8",None,"ESRI Shapefile")
1

I think there's a couple of issues:

  1. You need to escape your path if you're using single backslashes (use a double backslash at the end of your desired directory; or use single forward slashes; or add the r prefix before your path).

  2. Your second _writer command calls _vlayer which hasn't been defined (this command actually works).


So you could use the following:

vlayer = QgsVectorLayer("D:/KML-Images/dp0844061p.kml", "line", "ogr")

writer = QgsVectorFileWriter.writeAsVectorFormat(vlayer, "D:/KML-Images/dp0844061p.shp", "utf-8", None, "ESRI Shapefile")
0
0
inputPath=select kml Available Path+ "\\" 
inputPath = inputPath +  filename
#print inputPath
outputPath=select converted shape file storage Available Path + "\\" +  filename +".shp"
outputPath=self.FolderOutputPath +"\ Polygon_Shape\\" +  filename+".shp"

outputPath = outputPath.replace("\\","//")
print inputPath
print outputPath
vlayer = QgsVectorLayer(inputPath, filename+"_line", "ogr")

QgsMapLayerRegistry.instance().addMapLayer(vlayer)
_writer = QgsVectorFileWriter.writeAsVectorFormat(vlayer,outputPath ,"utf-8",None,"ESRI Shapefile")

QgsMapLayerRegistry.instance().removeMapLayer(vlayer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.