Read and write data to and from external files in Python

I have used VB script for 20 years and now using Python in Rhino 7.0 so quite a change for me. In the past I have used Rhino Save Settings and Rhino Get Settings to read data to and from INI style files. I now want to do this in Python so some advice as to the best approach to read data from external files would be appreciated.
Please keep it simple as my Python knowledge is still quite basic.

Here’s a GHPython component I wrote back in 2020 and still use, because back then the file reader component from Grasshopper didn’t work on macOS, and I believe still doesn’t.
It’s meant to read text files, but ini-ones should be no problem either. (4.6 KB)

Thanks for the file I will take a look, I really need to be able to read just specific data for a command from a file and not a complete file all at once. I am also working in Iron Python as a plug for Rhino 7, later I will try Rhino Code for Rhino 8 but I doubt that I will use GH.

Either way you’ll have to read the entire file to be able to search it and find the part that you’re looking for.

Mine is also written in IronPython. If you open de Grasshopper file, you can access it by double-clicking the GHPython component. It should work in Rhino, too.

What’s “Rhino Code”?

Python rhinoscriptsyntax has GetSettings() ; however it does not appear to have SaveSettings(). So you will probably need to learn a little about Python file reading and writing.

If you don’t need an .ini file structure, writing/reading a simple text file with information might do. Note also that within the same Rhino session, you can use the ‘Sticky’ dictionary to store and recall diverse kinds of data; you can also store and recall custom data in a Rhino file or on Rhino objects which is saved with the file and thus persists between sessions.

Hi @RogerD,

there is the ConfigParser module which you could use. Also note SafeConfigParser


Hi Thanks for the reply I shall look up the dictionary as it might be a way forward, i have dimensions of structural steel sections and pipe work fitting that I call from INI files and draw the component so want to update this to Python.

Thanks I didn’t even know about the Config Parser that may well be the answer I will read up on it and give it a go.

Thank you I didnt know I could open the GH file, I shall have a good look at your script.

rs.GetSettings() actually calls ConfigParser in the background.

Parsing the entire ini file is probably overkill to merely extract a specific piece of information. I’d read in the file and use a regular expression to get the relevant part.

Thanks I will see how it works.

Thanks for the suggestion