From 92e49eff5d5c51f5f2b8de98232a2396585f09a5 Mon Sep 17 00:00:00 2001 From: Anton Lodder Date: Wed, 7 Oct 2020 00:02:29 -0400 Subject: Support parsing paths specified with pathlib 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. --- rdflib/parser.py | 3 +++ test/test_parser_reads_from_pathlike_object.py | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 test/test_parser_reads_from_pathlike_object.py diff --git a/rdflib/parser.py b/rdflib/parser.py index 32e34f39..a6f155a6 100644 --- a/rdflib/parser.py +++ b/rdflib/parser.py @@ -12,6 +12,7 @@ want to do so through the Graph class parse method. import codecs import os +import pathlib import sys from io import BytesIO, TextIOBase, TextIOWrapper, StringIO, BufferedIOBase @@ -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): diff --git a/test/test_parser_reads_from_pathlike_object.py b/test/test_parser_reads_from_pathlike_object.py new file mode 100644 index 00000000..2d2114ca --- /dev/null +++ b/test/test_parser_reads_from_pathlike_object.py @@ -0,0 +1,26 @@ +import tempfile +import rdflib +from pathlib import Path + + +def test_reading_from_path_object(): + xml_sample = """\ + + + +""" + + 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 -- cgit v1.2.1