Python 3.4 で RDFLib を使用して RDF データを生成しようとしています。
最小限の例:
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'))
このコードにより、次のエラーが発生します。
file.write(g.serialize(format='turtle'))
TypeError : must be str, not bytes
最後の行を次のように置き換えると:
file.write(str(g.serialize(format='turtle')))
エラーは発生しませんが、結果はバイナリ ストリームの文字列表現 ( で始まる 1 行のテキスト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'
質問 グラフをファイルに正しくエクスポートするにはどうすればよいですか?