Shapefiles to AutoCAD DWG Using Python

29 Oct

This will be my last post on this topic. I will show how to create a DWG from a shapefile using python. This requires AutoCAD – as my other methods did not.  You will also need python, shapefile.py and pyautocad – and it’s dependency.

With AutoCAD open I run this code:

from pyautocad import Autocad, APoint
import shapefile

openshape = shapefile.Reader(“C:\Documents and Settings\user\Desktop\surveyShapefile”)
shpPoints = openshape.shapes()

acad = Autocad()

def readShapefile():
x = 0
while (x <= 100):
xy= shpPoints[x].points[0]
p1 = APoint(xy[0], xy[1])
acad.model.AddCircle(p1, .0001)
print ‘Reading Record: ‘+ str(x)
x=x+1

else:
print ‘Complete…’

readShapefile()

The result is my Survey in AutoCAD as points with the correct coordinates – coordinates from the GIS  in this case are WGS84.

We can modify the script by adding: acad.model.AddLine(p1, p2). This will convert a line shapefile to autoCAD. The code:

from pyautocad import Autocad, APoint
import shapefile

openshape = shapefile.Reader(“C:\Documents and Settings\user\Desktop\majorstreets”)
shpPoints = openshape.shapes()

acad = Autocad()

def readShapefile():
x = 0
while (x <= 5):
xy1 = shpPoints[x].points[0]
p1 = APoint(xy1[0], xy1[1])
xy2 = shpPoints[x].points[1]
p2= APoint(xy2[0], xy2[1])
acad.model.AddLine(p1, p2)
print ‘Reading Record: ‘+ str(x)
x=x+1

else:
print ‘Complete…’

readShapefile()

 

And the results:

 

You can use AutoLISP or probably .NET but Python is free and easy to learn.  Well, now you know another way to load shapefiles in to AutoCAD. With this in CAD, you can save it as a DWG and go straight to Revit.

And it does 3D:

from pyautocad import Autocad, APoint
acad = Autocad()

p1= APoint(10,10,10)
acad.model.AddCircle(p1, 10)

Let me state again that this code is sloppy – but functional. It is for demonstration purposes, so if you use it, clean it up and make the loops better.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: