title: How to export graph in RDF file using RDFLib
body: <p>I'm trying to generate RDF data using RDFLib in Python 3.4.</p>
  
  <p>A minimal example:</p>
  
  <pre class="lang-py prettyprint-override"><code>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'))
  </code></pre>
  
  <p>This code results in the following error:</p>
  
  <pre><code>file.write(g.serialize(format='turtle'))
  TypeError : must be str, not bytes
  </code></pre>
  
  <p>If I replace the last line with:
  </p>
  
  <pre><code>file.write(str(g.serialize(format='turtle')))
  </code></pre>
  
  <p>I do not get the error, but the result is a string representation of a binary stream (a single line of text starting with <code>b'</code>):</p>
  
  <pre><code>b'@prefix ns1: &lt;http://xmlns.com/foaf/0.1/&gt; .\n@prefix rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; .\n@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .\n@prefix xml: &lt;http://www.w3.org/XML/1998/namespace&gt; .\n@prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; .\n\n&lt;http://www.example.org#Alice&gt; a ns1:person ;\n    ns1:knows &lt;http://www.example.org#Bob&gt; .\n\n&lt;http://www.example.org#Bob&gt; a ns1:person .\n\n'
  </code></pre>
  
  <p><strong>Question</strong>
  How do I correctly export the graph into a file?</p>