1

I have a problem in creating some polylines in one Shapefile with PyShp 1.2. The plan is to read a GML file containing LineStrings and create a shapefile.

The theory is clear, but the realworld is different. As I understand the syntax is as follows:

w.line(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])

This one is a fixed line, but my lines are flexible. My thoughts were, to extract the Coordinates from the GML file and concatenate it to a String which meets the PyShape Syntax. My results are therefore:

[[[-94,-49.1152],[-94.45451,-49], .... ,[-93,-49.30391],[-94,-49.1152]]] <-- named "coords"

The idea in using s.line(parts=coords) failed due to needed float values.

The question here is, how to meet the syntax and stay flexible in the same way. Maybe my Python skills are still too basic, but the following links did not help:

Using pyshp to convert .csv file to .shp? <-- used points

Unable to create shapefile using shapefile.py <-- used also points

Using PyShp to convert polygons in *.csv to *.shp files? <-- comes close, but is fixed due to rectangles

Long story short: How can i create a polyline shape with lines of different length, based on coordinates available in variables.

I know that there are additional lines nessecary, but those are not the problem.

1
  • It might be better to use a library that understands GML than to try and parse it yourself. For example OGR or Fiona (which wraps OGR).
    – blah238
    Commented Oct 18, 2013 at 23:13

1 Answer 1

1

Matthias,

The pyshp syntax requires nested Python lists containing coordinates as floats. Your current approach is a string which simply looks like the syntax.

The quick, but not recommended, method would be to eval your string (very insecure):

linestr = "[[[-94,-49.1152],[-94.45451,-49],[-93,-49.30391],[-94,-49.1152]]]"
w.line(parts=eval(linestr))

The proper way would be to cast each coordinate pair to floats and append to a list:

coords=[["-94","-49.1152"],["-94.45451","-49"],["-93","-49.30391"],["-94","-49.1152"]]
line_parts = []
line = []
for x,y in coords:
    line.append([float(x),float(y)])
line_parts.append(line)
w.line(parts=line_parts)
1
  • Note - the first version of this answer had a typo in the line.append() method. It's fixed now. Commented Oct 19, 2013 at 0:00

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.