2011-08-28 9 views
3

いくつかの地理空間的なpythonを学ぼうとしています。多かれ少なかれ、クラスノートhereに従ってください。以下の私に与え無効なPythonの構文file.writeを使用して

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() 

ランニング:Pythonの2.7.1

実行

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

すべてのヘルプは素晴らしいだろう!また、単にスタイルのコメントを

y = str(geometry.GetY()) 

+0

@eyquem - ファイルとIDの両方がPython標準ライブラリで広く再利用されています機能に組み込まれています。非常に便利で説明的な名前です。 'file'はPython 3では削除されていますが、一般的にはPython 2でも使われていないので、避ける理由はほとんどありません。加えて、OPは英語をはっきりと理解していますし、Stack Overflowの_linguaフランチャもありますので、誰もが理解できるようにコメントを英語で投稿してください。 Foo Bahのコメントをフランス語で再掲する理由は全くありませんでした。 – agf

答えて

5

前のラインは閉じ括弧が欠落している、それが実際に意味を持っているので、それはPythonで変数名fileの使用を避けることをお勧めします。書き込み)新しいPythonのセッションを開いてhelp(file)

+0

うわー、それは明らかなことでした。本当にありがとう。 –

-1

1を実行してみてくださいidが文字列であることを確認します(Pythonは) 2大文字と小文字が区別されます)、あなたのコード内で大文字であってはならないはずです。 "cover"と "x"と "y"の場合と同じstr(id)を使用していない場合

+4

これらのものはどれも、「SyntaxError」ではなく、「AttributeError」または「TypeError」を引き起こします。 – agf

関連する問題