-
Notifications
You must be signed in to change notification settings - Fork 8
/
json2pickle.py
59 lines (51 loc) · 1.62 KB
/
json2pickle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
prog_ver = 'json2pickle v1.1 Copyright (c) 2019-2022 Matjaz Rihtar'
import sys, os
import ntpath
import traceback
import pickle, json
# -----------------------------------------------------------------------------
def ntdirname(path):
try:
head, tail = ntpath.split(path)
dirname = head or ntpath.dirname(head)
except: dirname = ''
if len(dirname) == 0: dirname = '.'
if dirname.endswith(os.sep):
return dirname
else:
return dirname + os.sep
# ntdirname
def ntbasename(path):
try:
head, tail = ntpath.split(path)
basename = tail or ntpath.basename(head)
except: basename = ''
return basename
# ntbasename
# =============================================================================
if __name__ == '__main__':
prog = ntbasename(sys.argv[0]).replace('.py', '').replace('.PY', '')
if len(sys.argv) < 2:
sys.exit('Usage: {} <file.json>'.format(prog))
try:
jpath = sys.argv[1]
fd = open(jpath, 'r', encoding='utf-8')
sys.stderr.write('Reading {}\n'.format(jpath))
data = json.load(fd)
fd.close()
ppath = jpath.replace('.json', '.pickle')
if not ppath.endswith('.pickle'):
ppath += '.pickle'
if os.path.isfile(ppath):
raise FileExistsError('File {} already exists'.format(ppath))
fd = open(ppath, 'wb')
sys.stderr.write('Writing {}\n'.format(ppath))
pickle.dump(data, fd)
fd.close()
except:
exc_type, exc_obj, exc_tb = sys.exc_info()
exc = traceback.format_exception_only(exc_type, exc_obj)
errmsg = '{}({}): {}'.format(prog, exc_tb.tb_lineno, exc[-1].strip())
sys.exit(errmsg)