persist.py
Go to the documentation of this file.
1 import json
2 
3 from schema import NoiseSpectrum
4 
5 # fixme: content here and in other "persist" submodules is repetitive and
6 # should be factored to common ground.
7 
8 def dumps(spectra, indent=4):
9  '''
10  Dump the spectra to a JSON string
11  '''
12  spectra = [s._asdict() for s in spectra]
13  return json.dumps(spectra, indent=indent)
14 
15 def loads(text):
16  '''
17  Return a list of NoiseSpectrum objects from the JSON text
18  '''
19  spectra = json.loads(text)
20  return [NoiseSpectrum(**s) for s in spectra]
21 
22 
23 def dump(filename, spectra):
24  '''
25  Save a list of wirecell.sigproc.noise.NoiseSpectrum objects to a
26  file of the given name.
27 
28  File is saved depending on extension. .json, .json.bz2 and
29  .json.gz are supported.
30  '''
31  text = dumps(spectra,indent=4)
32  if filename.endswith(".json"):
33  open(filename, 'w').write(text)
34  return
35  if filename.endswith(".json.bz2"):
36  import bz2
37  bz2.BZ2File(filename, 'w').write(text)
38  return
39  if filename.endswith(".json.gz"):
40  import gzip
41  gzip.open(filename, "wb").write(text)
42  return
43  raise ValueError("unknown file format: %s" % filename)
44 
45 def load(filename):
46  '''
47  Return a list of wirecell.sigproc.noise.NoiseSpectrum objects
48  loaded from the given file.
49 
50  File is loaded depending on extension. .json, .json.bz2 and
51  .json.gz are supported.
52  '''
53  if filename.endswith(".json"):
54  return loads(open(filename, 'r').read())
55 
56  if filename.endswith(".json.bz2"):
57  import bz2
58  return loads(bz2.BZ2File(filename, 'r').read())
59 
60  if filename.endswith(".json.gz"):
61  import gzip
62  return loads(gzip.open(filename, "rb").read())
63 
64  raise ValueError("unknown file format: %s" % filename)
def dumps(spectra, indent=4)
Definition: persist.py:8
def dump(filename, spectra)
Definition: persist.py:23
int open(const char *, int)
Opens a file descriptor.
size_t write(int, const char *, size_t)
Writes count bytes from buf to the filedescriptor fd.
int read(int, char *, size_t)
Read bytes from a file descriptor.