How to store pathlib paths in json file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: How to store pathlib paths in json file (/thread-12552.html) |
How to store pathlib paths in json file - Larz60+ - Aug-30-2018 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.
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:
RE: How to store pathlib paths in json file - snippsat - Aug-30-2018 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 callingThere 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' RE: How to store pathlib paths in json file - Larz60+ - Aug-30-2018 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:
|