使用file.write的Python语法无效

Jac*_*die 3 python geospatial

试图学习一些地理空间蟒蛇.或多或少遵循这里的课堂笔记.

我的守则

#!/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()
Run Code Online (Sandbox Code Playgroud)

运行它给我以下内容:

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

运行Python 2.7.1

任何帮助都会很棒!

Foo*_*Bah 5

上一行缺少一个右括号:

y = str(geometry.GetY())
Run Code Online (Sandbox Code Playgroud)

另外,只是一个样式注释:避免file在python中使用变量名是一个好主意,因为它实际上有意义.尝试打开一个新的python会话并运行help(file)