python script tool - use folder or file location under validation

2423
4
03-23-2018 12:53 PM
OrrGvili
Occasional Contributor

i have tool one of the parameter have is folder location (can be file it self) of jason file with parameters organized in dictionary 
i need to use this location under the" def updateParameters(self): " so i can open the  jason and load the parameters to the drop down menu 

this is the part that i cant figure if i used the real path with the dn like  dn = "c:/workspace"
it works great  but i need the path the user enter when the tool is used 


data= os.path.join(dn, 'data.json')
with open(data) as data_file:
dic = data.load(data_file)
self.params[3].filter.list = dic.keys()
return 

0 Kudos
4 Replies
Madanbhurati
Occasional Contributor

Hi,

If your Json file is placed under the same folder your python toolbox/script you can use "__File__" Attribute to get the current directory. Please try following code.

data= os.path.join(os.path.dirname(__file__),r'data.json')

0 Kudos
Madanbhurati
Occasional Contributor

Sorry, I miss understood your question, please review following code written for txt file, however you can change it for Json file. attached snapshot shows two parameters, Folder and List of Strings. Once you select the folder containing text file, using parameter "Add dialog box", your second parameter will be populated with text list.

 def updateParameters(self):
    user_path=self.params[0].value
    data =os.path.join(str(user_path),r'Msb.txt')
    results = []
    with open(data) as data_file:
    for line in data_file:
         results.append(line)
         self.params[1].filter.list = results
    return

OrrGvili
Occasional Contributor

thanks 
Last night found the solution
part of the problem was   that self.params[0].value throw exception 

when change it to  "with open(self.params[3].value.value) as data_file:"  solved the problem 

.value vs .value.value


philnagel
Regular Contributor

I think you could probablu use .valueAsText instead of value.value. Thwat way, you would get the file path as string to pass to open().

0 Kudos