[英]Invalid Python syntax using file.write
Trying to learn some geospatial python. 试图学习一些地理空间蟒蛇。 More or less following the class notes here . 或多或少遵循这里的课堂笔记。
#!/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 运行Python 2.7.1
Any help would be fantastic! 任何帮助都会很棒!
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. 另外,只是一个样式注释:避免在python中使用变量名file
是一个好主意,因为它实际上有意义。 Try opening a new python session and running help(file)
尝试打开一个新的python会话并运行help(file)
1)write should shouldn't be upper case in your code (Python is case sensitive) 2)make sure id is a string; 1)写代码不应该是大写(Python区分大小写)2)确保id是一个字符串; if it's isn't use str(id) in your term, same for "cover" and "x" and "y" 如果你的术语中没有使用str(id),那么“cover”,“x”和“y”也是如此
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.