Skip to content

Instantly share code, notes, and snippets.

@randerzander
Last active September 9, 2015 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randerzander/43fbdfe1ba227ebffe73 to your computer and use it in GitHub Desktop.
Save randerzander/43fbdfe1ba227ebffe73 to your computer and use it in GitHub Desktop.
export dbf to csv file
#!/usr/bin/python
import sys, pyproj, shapefile
input_file = sys.argv[1]
output_file = sys.argv[2]
source_spatialref = sys.argv[3]
target_spatialref = sys.argv[4]
sf = shapefile.Reader(input_file)
shapes = sf.shapes()
f = open(output_file, 'w')
def quote(token):
if ',' in token: return '"' + token + '"'
else: return token
f.write(','.join([quote(x[0]) for x in sf.fields] + ['lat', 'lng']) + '\n')
# Examples: 'ESRI:102667', 'WGS84' from spatialreference.org
source_proj = pyproj.Proj(init=source_spatialref, preserve_units=True)
target_proj = pyproj.Proj(proj='latlong', datum=target_spatialref, ellps=target_spatialref)
for idx, record in enumerate(sf.records()):
lng,lat = pyproj.transform(source_proj, target_proj, shapes[idx].points[0][0], shapes[idx].points[0][1])
f.write(','.join(map(lambda x: quote(str(x).strip()), record) + [str(lat), str(lng)]) + '\n')
f.close()
@randerzander
Copy link
Author

pip install pyproj
pip install shapefile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment