gpt4 book ai didi

python - 使用 file.write 的 Python 语法无效

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:47 25 4
gpt4 key购买 nike

尝试学习一些地理空间 python。或多或少遵循类笔记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()

运行得到以下结果:

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

运行 Python 2.7.1

任何帮助都会很棒!

最佳答案

上一行缺少右括号:

y = str(geometry.GetY())

此外,只是一个风格注释:避免在 python 中使用变量名 file 是个好主意,因为它实际上是有意义的。尝试打开一个新的 Python session 并运行 help(file)

关于python - 使用 file.write 的 Python 语法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7223570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com