4

Trying to learn some geospatial python. More or less following the class notes here.

My Code

#!/usr/bin/python

# import modules
import ogr, sys, os

# set working dir
os.chdir('/home/jacques/misc/pythongis/data')

# create the text file we're writing to
file = open('data_export.txt', 'w')

# import the required driver for .shp
driver = ogr.GetDriverByName('ESRI Shapefile')

# open the datasource
data = driver.Open('road_surveys.shp', 1)
if data is None:
    print 'Error, could not locate file'
    sys.exit(1)

# grab the datalayer
layer = data.GetLayer()

# loop through the features
feature = layer.GetNextFeature()
while feature:

    # acquire attributes
    id = feature.GetFieldAsString('Site_Id')
    date = feature.GetFieldAsString('Date')

    # get coordinates
    geometry = feature.GetGeometryRef()
    x = str(geometry.GetX())
    y = str(geometry.GetY()

    # write to the file
    file.Write(id + ' ' + x + ' ' + y + ' ' + cover + '\n')

    # remove the current feature, and get a new one
    feature.Destroy()
    feature = layer.GetNextFeature()

# close the data source
datasource.Destroy()
file.close()

Running that gives me the following:

  File "shape_summary.py", line 38
    file.write(id + ' ' + x + ' ' + y + ' ' + cover + '\n')
       ^
SyntaxError: invalid syntax

Running Python 2.7.1

Any help would be fantastic!

1
  • @eyquem - both file and id are widely reused in the Python standard library despite being builtin functions -- they're very useful and descriptive names. file has been removed in Python 3, and is not generally used even in Python 2, so there is very little reason to avoid it. In addition, the OP clearly understands English, and it's also the lingua franca of Stack Overflow, so please post comments in English so everyone can understand them. There was really no reason to restate Foo Bah's comment in French. Commented Aug 28, 2011 at 22:25

2 Answers 2

6

Previous line is missing a close parenthesis:

y = str(geometry.GetY())

Also, just a style comment: it's a good idea to avoid using the variable name file in python because it actually has a meaning. Try opening a new python session and running help(file)

Sign up to request clarification or add additional context in comments.

1 Comment

Ugh, figured it was something obvious. Thanks so much.
-1

1)write should shouldn't be upper case in your code (Python is case sensitive) 2)make sure id is a string; if it's isn't use str(id) in your term, same for "cover" and "x" and "y"

1 Comment

None of those things would cause a SyntaxError but rather an AttributeError or TypeError.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.