使用file.write时的无效Python语法

4 投票
2 回答
8903 浏览
提问于 2025-04-17 00:29

我正在尝试学习一些与地理空间相关的Python知识。大致上是根据课堂笔记在学习,笔记可以在这里找到。

这是我的代码

#!/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 个回答

-1

1) 在你的代码中,"write"这个词的首字母不应该大写,因为Python对大小写是很敏感的。

2) 确保"id"是一个字符串;如果不是的话,可以用str(id)来转换,"cover"、"x"和"y"也是一样的处理。

6

上一行缺少一个闭合的括号:

y = str(geometry.GetY())

另外,有个风格上的建议:在Python中最好不要使用变量名 file,因为它实际上是有特定含义的。你可以试着打开一个新的Python会话,然后运行 help(file) 来看看。

撰写回答