5

I'm trying to write a standalone script that writes a shapefile (using QGIS 3.0.2). I've tried something like :

from qgis.core import *
from qgis.PyQt.QtCore import QVariant
from qgis.utils import QGis


QgsApplication.setPrefixPath("/usr/bin/qgis", True)
qgs = QgsApplication([], False)

qgs.initQgis()

fields = QgsFields()
fields.append(QgsField("ID_HYD", QVariant.Int))
fields.append(QgsField("SBD_KM2", QVariant.Double))


writer = QgsVectorFileWriter("/home/sylvain/test.shp",
                             "CP1250",
                             fields,
                             QGis.WKBPoint,
                             None,
                             "ESRI Shapefile")

qgs.exitQgis()

The issue is as follow :

/usr/bin/python3.5 /home/sylvain/test.py
Must construct a QGuiApplication first.

Process finished with exit code 1

Is there a way to write a shapefile on drive without constructing a GUIApplication ?

If not, how should I do do create such an item ?

1
  • 1
    Did my advice provide any help?
    – Basile
    May 19, 2018 at 19:42

3 Answers 3

5

You are getting the error in line 3 from qgis.utils import QGis. In QGIS 3, geometry types is specified by QgsWkbTypes enum in core library. Thus, remove from qgis.utils import QGis

Use script in the following way. Notice highlighted lines with ####.

from qgis.core import *
from qgis.PyQt.QtCore import QVariant
# from qgis.utils import QGis  # REMOVE THIS LINE ####

QgsApplication.setPrefixPath("/usr/bin/qgis", True)
qgs = QgsApplication([], False)

qgs.initQgis()

fields = QgsFields()
fields.append(QgsField("ID_HYD", QVariant.Int))
fields.append(QgsField("SBD_KM2", QVariant.Double))


writer = QgsVectorFileWriter("/home/sylvain/test.shp",
                             "CP1250",
                             fields,
                             QgsWkbTypes.Point, #### instead of QGis.WKBPoint
                             QgsCoordinateReferenceSystem(), #### instead of None
                             "ESRI Shapefile")

qgs.exitQgis()
4

One of the easiest python libraries to read/write shapefiles is pyshp. You can install it with pip:

pip install pyshp

After you can import the library and create your shapefile:

import shapefile

out_file = 'test.shp'

# Set up a shapefile writer
writer = shapefile.Writer(shapeType=shapefile.POINT)
# Create empty fields
writer.field("ID_HYD", "N")  # integer field - see pyshp docs
writer.field("SBD_KM2", "F")  # float field - see pyshp docs

# Save shapefile
writer.save(out_file)

These links may help you to get started:

  1. Official pyshp docs
  2. Another library to create shapefiles with python - ogr
2

Just use FIONA a python wrapper for OGR and allows you to build and convert any data. Or just OGR2OGR

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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