Skip to content

Commit

Permalink
Support parsing paths specified with pathlib
Browse files Browse the repository at this point in the history
pathlib was added to the standard librarly as of Python 3.4.
This adds support for calling Graph.parse on a file specified
using a pathlib object.
  • Loading branch information
AnjoMan committed Oct 7, 2020
1 parent 56dc420 commit 92e49ef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions rdflib/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import codecs
import os
import pathlib
import sys

from io import BytesIO, TextIOBase, TextIOWrapper, StringIO, BufferedIOBase
Expand Down Expand Up @@ -221,6 +222,8 @@ def create_input_source(
else:
if isinstance(source, str):
location = source
elif isinstance(source, pathlib.Path):
location = str(source)
elif isinstance(source, bytes):
data = source
elif hasattr(source, "read") and not isinstance(source, Namespace):
Expand Down
26 changes: 26 additions & 0 deletions test/test_parser_reads_from_pathlike_object.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import tempfile
import rdflib
from pathlib import Path


def test_reading_from_path_object():
xml_sample = """\
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/2013/CIM-schema-cim16#"
xmlns:cyme="http://www.cyme.com/CIM/1.0.2#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
<cim:SwitchInfo rdf:ID="_AB16765A-B19E-4454-A58F-868D23C6CD26" />
</rdf:RDF>"""

with tempfile.TemporaryDirectory() as td:
sample_file = Path(td) / "sample.xml"
open(str(sample_file), 'w').write(xml_sample)

g = rdflib.Graph()
g.parse(sample_file, publicID="")

subject, predicate, object = next(iter(g))

assert "_AB16765A-B19E-4454-A58F-868D23C6CD26" in subject
assert "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" in predicate
assert "http://iec.ch/TC57/2013/CIM-schema-cim16#SwitchInfo" in object

0 comments on commit 92e49ef

Please sign in to comment.