Неверный синтаксис Python с использованием file.write - PullRequest
3 голосов
/ 29 августа 2011

Попытка выучить некоторый геопространственный питон. Более или менее следуя указаниям класса здесь .

Мой код

#!/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()

Запуск, который дает мне следующее:

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

Запуск Python 2.7.1

Любая помощь была бы фантастической!

Ответы [ 2 ]

5 голосов
/ 29 августа 2011

В предыдущей строке отсутствует закрывающая скобка:

y = str(geometry.GetY())

Кроме того, просто комментарий стиля: хорошая идея избегать использования имени переменной file в python, потому что оно действительно имеет значение Попробуйте открыть новый сеанс Python и запустить help(file)

0 голосов
/ 29 августа 2011

1) запись не должна быть заглавной в вашем коде (Python чувствителен к регистру) 2) убедитесь, что id является строкой; если это не использовать str (id) в вашем термине, то же самое для "cover" и "x" и "y"

...