Search code examples
python-3.xgraphprotege

Modify a protege file from python


I'm a beginner in protege and python. I created an owl file in protege. And now I'm trying to modify that file with python, adding some new triples. But it does't show me any change in the original file. this is the code that i tried so far: Thanks in advance for any help.

g = Graph()
n = Namespace('http://www.../')
result = g.parse('file_name', format ="application/rdf+xml" )

with open ('file_name.owl', 'r+') as a, open('another_filename.txt') as b: 
    if(some_condition) in g:
        for item in b:
            g.add([the triple])
        print('name added')

Solution

  • Your implementation only contains a file read but not write - so your original file can't be changed. In order to change the original file, you have to explicitly write your graph back to that file.

    Assuming that you are using a library such as RDFLib/rdflib the following change has to be made in order to "update" your graph:

    from rdflib import Graph, ...
    
    # read graph
    g = Graph()
    result = g.parse('./foo.owl', format ="application/rdf+xml" )
    
    # add some triples based on your logic
    # ...
    
    # persist graph to disk
    g.serialize("./foo.owl", format="xml")
    

    By the way - this applies not only specifically to semantic web graphs but to I/O in Python in general (e.g. read/write normal text, CSVs, data base records,...).