Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export graph in RDF file using RDFLib

I'm trying to generate RDF data using RDFLib in Python 3.4.

A minimal example:

from rdflib import Namespace, URIRef, Graph
from rdflib.namespace import RDF, FOAF

data = Namespace("http://www.example.org#")

g = Graph()

g.add( (URIRef(data.Alice), RDF.type , FOAF.person) )
g.add( (URIRef(data.Bob), RDF.type , FOAF.person) )
g.add( (URIRef(data.Alice), FOAF.knows, URIRef(data.Bob)) )

#write attempt
file = open("output.txt", mode="w")
file.write(g.serialize(format='turtle'))

This code results in the following error:

file.write(g.serialize(format='turtle'))
TypeError : must be str, not bytes

If I replace the last line with:

file.write(str(g.serialize(format='turtle')))

I do not get the error, but the result is a string representation of a binary stream (a single line of text starting with b'):

b'@prefix ns1: <http://xmlns.com/foaf/0.1/> .\n@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n@prefix xml: <http://www.w3.org/XML/1998/namespace> .\n@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n<http://www.example.org#Alice> a ns1:person ;\n    ns1:knows <http://www.example.org#Bob> .\n\n<http://www.example.org#Bob> a ns1:person .\n\n'

Question How do I correctly export the graph into a file?

like image 757
Arthur Vaïsse Avatar asked May 07 '14 14:05

Arthur Vaïsse


People also ask

How do I read an RDF file?

Notepad++, or any advanced text editor for that matter, opens RDF files. The structure of each RDF file depends on the serialization used. Show activity on this post. The only way to achieve this is to convert the binary into a text format.

What is RDFLib in Python?

RDFLib is a Python library for working with RDF, a simple yet powerful language for representing information. This library contains parsers/serializers for almost all of the known RDF serializations, such as RDF/XML, Turtle, N-Triples, & JSON-LD, many of which are now supported in their updated form (e.g. Turtle 1.1).


1 Answers

The serialize method accepts a destination keyword that is a file path. In your example, you would want to use:

g.serialize(destination='output.txt', format='turtle')

Instead of

file = open("output.txt", "w")
file.write(g.serialize(format='turtle'))
like image 94
Ted Lawless Avatar answered Sep 20 '22 15:09

Ted Lawless