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


Messages In This Thread
How to store pathlib paths in json file - by Larz60+ - Aug-30-2018, 04:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to get directory information with pathlib Larz60+ 0 3,637 Oct-21-2017, 12:18 PM
Last Post: Larz60+
  Practical use of pathlib Larz60+ 0 3,455 Oct-17-2017, 09:54 AM
Last Post: Larz60+
  JSON file with links for each US state Open Data Page Larz60+ 5 5,856 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