Opening a file in Python script

Hi,

Can anyone describe to me why the python script below will not work? What I simply want to achieve is inserting a filepath to a python script and the script loads it in json format.

Hi,

I’m not exactly sure, since you provided no files to test this, but I guess that the file path that you provide on line 3 is wrong. Calling str(“r”+filePath) results in a string “rH:\TREX_JSON…”, which is probably not the same as calling open(r"H:\TREX_JSON…"), where the parameter r is not a string but an abbreviation for “read”.

You could try this instead and built upon it:

import json

with open(filePath) as json_data:
    data = json.load(json_data)
    print(data)

Furthermore, when you use the “with” statement with the “open” function, you do not need to close the file at the end, because “with” would automatically close it for you.

I’m sort of on the limits of a confidentiality agremeent just by posting this picture :frowning:

The str("r"+filePath) result is shown in the python component below which is r"H:\TREX_JSON... and that should be correct. I also tried manually swapping the backslashes to forwardslashes. The reason why I’m posting here since the filepaths in both scripts (up & below) should have the exact same filepath for open but only one works; the one with manually inserted path.

Also thanks for the tips but I tested your script and nothing changes. Both yours and my script work if I replace the filepath manually as a text but if I wish to insert the filepath from an external (panel or param) source it’s not working… :confused:

Ah, I just tested using filepath param and setting it for Select one existing file and it works. Outputted string seems to be the same so I’m still puzzled by this but atleast it works a little better now…

What you could also try is loading the directory/folder of your JSON files straight into the Python component, without panel inputs or any input from the GH canvas, and compile the absolute paths of the files in Python.

import os

json_dir = os.path.join("H:", "TREX_JSON") # os.path module functions always select the correct configuration for your OS
json_fpaths = [] # list for storing the absolute paths of your json files

for f in os.listdir(json_dir): # loop each file in the directory
    if f.endswith(".json"): # if the file is a json file...
        f_path = os.path.join(json_dir, f) # ... compile an absolute path
        json_fpaths.append(f_path) # save the path in the list

The absolute path of each of your JSON files would be compiled and saved in the list json_fpaths.
Calling os.path.join(“H:”, “TREX_JSON”), instead of “H:\TREX_JSON”, to compile your directory path, might help since it automatically choses the right configuration and formatting.

Thanks for all the python advice! I’ll test this method also, this could be very suitable for my purposes :slight_smile:

1 Like