Python Forum
How to store pathlib paths in json file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to store pathlib paths in json file
#1
This took me a while to figure out, woludn't have 15 years ago, but the result is quite simple:

I wanted to store pathlib objects in a json file, so that I can use as objects when reading the file back in.
  • The script below will create a 'data' directory one level higher than current directory, or use existing 'data' directory if already there.
  • within that directory, will create a json directory which will contain two differently named, but each with identical contents, which is a dictionary containing two pathlib paths.
  • load that json file back into a new dictionary (with json load)
  • use one of the pathlib links to read the other json file as plain text
  • Print the text

Here's the solution:
import json
from pathlib import Path
import os



def json_writer():
    os.chdir(os.path.dirname(__file__))
    homepath = Path('.')

    datapath = homepath / 'data'
    datapath.mkdir(exist_ok=True)

    jsonpath = datapath / 'json'
    jsonpath.mkdir(exist_ok=True)

    file1 = jsonpath / 'TestPath1.json'
    file2 = jsonpath / 'TestPath2.json'

    pathdict = {
        'path1': str(file2),
        'path2': str(file1),
    }

    with file1.open('w') as fp:
        json.dump(pathdict, fp)

    with file2.open('w') as fp:
        json.dump(pathdict, fp)

    newdict = {}
    with file2.open() as fp:
        newdict = json.load(fp)

    filename = Path(newdict['path1'])
    with filename.open() as fp:
        text = fp.read()
    print(text)


if __name__ == '__main__':
    json_writer()
And the results are:
Output:
{"path1": "data/json/TestPath2.json", "path2": "data/json/TestPath1.json"}
Reply
#2
Some addition info in 3.6 --> there is os.fspath(path)
Why is this there?
Just so can avoid str(file2).

I also wonder when used pathlib how to get a string output,so i use str(path) to go from Path object to a string.
It worked okay,but remember thinking that it's something not right about it.

There even a own PEP just for this PEP 519.
519 Wrote:This lack of support required users of pathlib to manually convert path objects to strings by calling str(path) which many found error-prone.

One issue in converting path objects to strings comes from the fact that the only generic way to get a string representation of the path was to pass the object to str().
This can pose a problem when done blindly as nearly all Python objects have some string representation whether they are a path or not,
e.g. str(None) will give a result that builtins.open() [5] will happily use to create a new file.
There also added __fspath__().
E:\div_code
λ ptpython
>>> from pathlib import Path
>>> import os

>>> working_dir = Path.cwd()

>>> working_dir
WindowsPath('E:/div_code')

>>> os.fspath(working_dir)
'E:\\div_code'

>>> working_dir.__fspath__()
'E:\\div_code'

# All this to avoid this
>>> str(working_dir)
'E:\\div_code'
Reply
#3
modified with os.fspath looks better
import json
from pathlib import Path
import os



def json_writer():
    os.chdir(os.path.dirname(__file__))
    homepath = Path('.')

    datapath = homepath / 'data'
    datapath.mkdir(exist_ok=True)

    jsonpath = datapath / 'json'
    jsonpath.mkdir(exist_ok=True)

    file1 = jsonpath / 'TestPath1.json'
    file2 = jsonpath / 'TestPath2.json'

    pathdict = {
        'path1': os.fspath(file2),
        'path2': os.fspath(file1),
    }

    with file1.open('w') as fp:
        json.dump(pathdict, fp)

    with file2.open('w') as fp:
        json.dump(pathdict, fp)

    newdict = {}
    with file2.open() as fp:
        newdict = json.load(fp)

    filename = Path(newdict['path1'])
    with filename.open() as fp:
        text = fp.read()
    print(text)


if __name__ == '__main__':
    json_writer()
still works fine:
Output:
{"path1": "data/json/TestPath2.json", "path2": "data/json/TestPath1.json"} (venv) Larz60p@linux-nnem: EncodePathlibPathJson:$
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to get directory information with pathlib Larz60+ 0 3,603 Oct-21-2017, 12:18 PM
Last Post: Larz60+
  Practical use of pathlib Larz60+ 0 3,403 Oct-17-2017, 09:54 AM
Last Post: Larz60+
  JSON file with links for each US state Open Data Page Larz60+ 5 5,749 Mar-05-2017, 11:19 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020