[英]Invalid Python syntax using file.write
試圖學習一些地理空間蟒蛇。 或多或少遵循這里的課堂筆記。
#!/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會話並運行help(file)
1)寫代碼不應該是大寫(Python區分大小寫)2)確保id是一個字符串; 如果你的術語中沒有使用str(id),那么“cover”,“x”和“y”也是如此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.