forked from conda-archive/conda-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathos1_hw.py
48 lines (37 loc) · 1.12 KB
/
os1_hw.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# http://www.gis.usu.edu/~chrisg/python/2008/os1_hw.py
# os1_hw.py
# Solution to Open Source week 1 homework -- reading vector data
# cgarrard 1-31-08
import ogr, sys, os
# set the working directory and filenames
# os.chdir('d:/data/classes/python/os1')
dataFn = 'sites.shp'
outFn = 'sites_coords.txt'
# open the output file
outFile = open(outFn, 'w')
# open the datasource
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open(dataFn, 0)
if dataSource is None:
print('Could not open ' + dataFn)
sys.exit(1)
# get the layer and loop through the features
layer = dataSource.GetLayer()
feature = layer.GetNextFeature()
while feature:
# get the attributes
id = feature.GetFieldAsString('id')
cover = feature.GetFieldAsString('cover')
# get the point coordinates
geometry = feature.GetGeometryRef()
x = geometry.GetX()
y = geometry.GetY()
# print the info
outFile.write(id + ' ' + str(x) + ' ' + str(y) + ' ' + cover + '\n')
# get the next feature
feature.Destroy()
feature = layer.GetNextFeature()
# close the datasource and file
dataSource.Destroy()
outFile.close()
print("END os1_hw.py")