我有以下代碼,它使用我需要的數據從shp.file創建需要的txt文件。我有一個名爲profile的文件夾,其中包含一些名爲(profil1.shp,profil2.shp,profil3.shp等)的形狀文件。我想知道如何創建一個循環,以便腳本爲每個文件創建一個具有相同名稱的txt文件(例如,用於profil1.shp創建profil1.txt,profil2.shp創建profil2.txt等)。腳本通過目錄中的文件循環
import ogr, os, sys, osr
os.chdir('..\profiles')
file = open('profil1.txt', 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open('profil1.shp', 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
編輯:代碼返回一個無法打開的文件。 Photo of the folder containing the files and their respective names. Safe to assume I am doing something wrong.
import ogr, os, sys, osr,os.path
os.chdir = ('C:\Users\Andrei\Desktop\profil3')
l = os.listdir('C:\Users\Andrei\Desktop\profil3')
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
謝謝你的回答,但我是一個相當新的用戶python和腳本我使用我從一個例子適應我的需要。你或其他人是否善意地展示了整個代碼應該是什麼樣子,如果問題不是太多,我似乎無法從我嘗試過的任何結果中獲得任何結果,而且我需要此腳本來避免手動導出每個文件。再次感謝併爲此造成的不便表示歉意! –
更新了答案,請現在檢查。 –