Hi Dan & Neil, ok, here comes the whole script. It might look in some parts familiar, still dealing with my profiles. But at least it's in general working fine....:
That the _location variable had the underscore is only due to the programming habits of my colleague...(doesn't make a difference)
import arcpy
import os
import numpy as np
import unicodedata
import codecs
import csv
arcpy.env.overwriteOutput= True
location_for_tables = arcpy.GetParameterAsText(0)
DirOutTables= arcpy.GetParameterAsText(1)
def FindFiles(location):
arcpy.env.workspace = location
ListFiles=arcpy.ListFiles("*.txt")
return ListFiles
def unique_values(table, field):
with arcpy.da.SearchCursor(table, [field]) as cursor:
return sorted({row[0] for row in cursor})
def CreateTableView(location, filename):
arcpy.env.overwriteOutput = True
complete_filename = os.path.join(location, filename)
arcpy.MakeTableView_management(complete_filename, "kibu_tview")
return "kibu_tview"
def store_table(table):
arcpy.AddMessage("open "+table)
profile_nrs=unique_values(table, "Station")
arcpy.AddMessage(profile_nrs)
desc = arcpy.Describe(table)
fieldnames=[field.name.encode("utf-8") for field in desc.fields]
tablefile=location_for_tables+"\\"+table
for profile in profile_nrs:
if profile >0:
expression="Station="+str(profile)
print(expression)
with arcpy.da.SearchCursor(table,"*",expression) as sCursor:
for sRow in sCursor:
table_name=str(sRow[0])+"_"+str(sRow[1])+".txt"
filepath=DirOutTables +"\\"+ table_name
UIDvalue=str(sRow[0])+"_"+str(sRow[1])
break
if arcpy.Exists(filepath):
arcpy.AddMessage("Table "+table_name+" exists")
else:
with open(tablefile, 'r') as t:
with open(filepath, 'a') as f:
w = csv.writer(f, delimiter="\t", lineterminator='\n')
r = csv.reader(t, delimiter="\t")
all=[]
header=r.next()
header.append('UPI')
all.append(header)
for sRow in sCursor:
sRow=sRow + (UIDvalue,)
all.append(sRow)
w.writerows(all)
del sRow
arcpy.AddMessage("Table "+table_name+" created")
else:
print("empty line")
def main():
location_for_tables = arcpy.GetParameterAsText(0)
DirOutTables= arcpy.GetParameterAsText(1)
list_of_files = FindFiles(location_for_tables)
if len(list_of_files)==0:
arcpy.AddError("list empty")
sys.exit()
else:
arcpy.AddMessage(list_of_files)
for each_file in list_of_files:
store_table(each_file)
if __name__ == '__main__':
main()
I don't see why the script should work in PyScripter, in the command window, in the python window in ArcGIS but not as a tool even if don't use any parameters.
The difference I find between executing the tool and the same script in cmd is that in ArcGIS it does not put the paths in "path comes here" but in cmd they are required.