36. saveload
— A multifunctional file format for saving pyFormex geometry or projects.¶
This module defines the PzfFile class which is the new implementation of the PZF file format.
36.1. Classes defined in module saveload¶
-
class
saveload.
Config
[source]¶ A very simple config parser.
This class contains two static functions: ‘dumps’ to dump a dict to a string, and ‘loads’ to load back the dict from the string.
The string format is such that it can easily be read and edited. Each of the items in the dict is stored on a line of the form ‘key = repr(value)’. On loading back, each line is split on the first appearance of a ‘=’. The first part is stripped and used as key, the second part is eval’ed and used as value.
-
class
saveload.
PzfFile
(filename)[source]¶ An archive file in PZF format.
PZF stands for ‘pyFormex zip format’. A complete description of the format and API is given in pyFormex file formats.
This is the implementation of version 2.0 of the PZF file format. The format has minor changes from the (unpublished) 1.0 version and is able to read (but not write) the older format.
A PZF file is actually a ZIP archive, written with the standard Python ZipFile module. Thus, its contents are individual files. In the current format 2.0, the PzfFile writer creates only three types of files, marked by their suffix:
.npy: a file containing a single NumPy array in Numpy’s .npy format;
.txt: a file containing text in a utf-8 encoding;
no suffix: an empty file: the info is in the file name.
The filename carry important information though. Usually they follow the scheme name__class__attr, where name is the object name, class the object’s class name (to be used on loading) and attr is the name of the attribute that has its data in the file. Files without suffix have their information in the filename.
Saving objects to a PZF file is as simple as:
PzfFile(filename).save(**kargs)
Each of the keyword arguments provided specifies an object to be saved with the keyword as its name.
To load the objects from a PZF file, do:
dic = PzfFile(filename).load()
This returns a dict containing the pyFormex objects with their names as keys.
Limitations: currently, only objects of the following classes can be stored: str, dict, numpy.ndarray, Coords, Formex, Mesh, TriSurface, PolyLine, BezierSpline, CoordSys, Camera, Canvas settings. Using the API (see pyFormex file formats) this can however easily be extended to any other class of objects.
- Parameters
filename (path_like) – Name of the file from which to load the objects. It is normally a file with extension ‘.pzf’.
Notes
See also the example SaveLoad.
-
write_objects
(savedict, *, compress=False, mode='w')[source]¶ Save a dict to a PZF file
- Parameters
savedict (dict) – Dict with objects to store. The keys should be valid Python variable names. The values should be str, dict or array_like. If a dict, it should be json serializable.
-
save
(_camera=False, _canvas=False, _compress=False, _add=False, **kargs)[source]¶ Save pyFormex objects to the PZF file.
- Parameters
kargs (keyword arguments) – The objects to be saved. Each object will be saved with a name equal to the keyword argument. The keyword should not end with an underscore ‘_’, nor contain a double underscore ‘__’. Keywords starting with a single underscore are reserved for special use and should not be used for any other object.
Notes
Reserved keywords: - ‘_camera’: stores the current camerasettings - ‘_canvas’: stores the full canvas layout and camera settings - ‘_compress’
Examples
>>> with utils.TempDir() as d: ... pzf = PzfFile(d / 'myzip.pzf')
See also example SaveLoad.
-
add
(**kargs)[source]¶ Add objects to an existing PZF file.
This is a convenient wrapper of
save()
with the _add argument set to True.
-
read_files
(files=None)[source]¶ Read files from a ZipFile
- Parameters
files (list, optional) – A list of file filenames to read. Default is to read all files.
- Returns
dict – A dict with the filenames as keys and the interpreted file contents as values. Files ending in ‘.npy’ are returned as a numpy array. Files ending in ‘.txt’ are returned as a (multiline) string except if the stem of the filename ends in one of ‘:c’, ‘:j’ or ‘:r’, in which case a dict is returned.
See also
load
read files and convert the contents to pyFormex objects.
-
load
(objects=None)[source]¶ Load pyFormex objects from a file in PZF format
- Returns
dict – A dict with the objects read from the file. The keys in the dict are the object names used when creating the file.
Notes
If the returned dict contains a camera setting, the camera can be restored as follows:
if '_camera' in d: pf.canvas.initCamera(d['_camera']) pf.canvas.update()
See also example SaveLoad.
See also
read
read files and return contents as arrays, dicts and strings.
-
zip
(path, files=None, compress=False)[source]¶ Zip files from a given path to a PzfFile
This shold only be used on a dict extracted from a PZF file.
-
convert
(compress=None)[source]¶ Convert a PZF file to the current format.
- Parameters
compress (bool) – Specifies whether the converted file should use compression. If not provided, compression will be used if the old file did.
Notes
Newer versions can convert files written with older versions, but the reverse is not necessarily True.
convert can also be used to compress a previously uncompressed PZF file of the same version.
36.2. Functions defined in module saveload¶
-
saveload.
dict2str
(d, fmt)[source]¶ Nicely format a dict so it can be imported again
Examples
>>> d = {'a': 0, 'b': (0,1), 'c': 'string'} >>> print(dict2str(d, 'c')) a = 0 b = (0, 1) c = 'string' >>> print(dict2str(d, 'j')) {"a": 0, "b": [0, 1], "c": "string"} >>> print(dict2str(d, 'r')) {'a': 0, 'b': (0, 1), 'c': 'string'}
-
saveload.
path_split
(path)[source]¶ Split a path in directory, filename, suffix
- Returns
path (str) – The part of the string before the last ‘/’. An empty string if there is no ‘/’.
stem (str) – The part between the last ‘/’ and the last ‘.’ after it or the end of the string if there is no ‘.’.
suffix (str) – The part after the last ‘.’ or empty if there is no ‘.’ after the last ‘/’.
Examples
>>> path_split('aa/bb.cc') ('aa', 'bb', 'cc') >>> path_split('aa/bb') ('aa', 'bb', '') >>> path_split('bb.cc') ('', 'bb', 'cc') >>> path_split('bb') ('', 'bb', '') >>> path_split('dir.0/dir.1/ar.2.suf') ('dir.0/dir.1', 'ar.2', 'suf')
-
saveload.
register
(clas)[source]¶ Register a class in the pzf i/o module
A registered class can be exported to a PZF file.
- Returns
class – The provided class is returned, so that this method can be used as a decorator. Normally though, one uses the
utils.pzf_register()
as decorator.
-
saveload.
str2dict
(s, fmt)[source]¶ Read a dict from a string representation
Examples
>>> s = "{'a': 0, 'b': (0,1), 'c': 'string'}"
-
saveload.
zipfile_write_array
(zipf, fname, val, datetime=None, compress=False)[source]¶ Write a numpy array to an open ZipFile
- Parameters
zipf (ZipFile) – A ZipFIle that is open for writing.
fname (str) – The filename as it will be set in the zip archive.
val (ndarray) – The data to be written into the file. It should be a numpy.ndarray or data that can be converted to one.
datetime (tuple, optional) – The date and time mark to be set on the file. It should be a tuple of 6 ints: (year, month, day, hour, min, sec). If not provided, the current date/time is used.
compress (bool, optional) – If True, the data will be compressed with the zipfile.ZIP_DEFLATED method.