39. pzffile — 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.

39.1. Classes defined in module pzffile

class pzffile.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.

static dumps(d)[source]

Dump a dict to a string in Config format.

static loads(s)[source]

Load a dict from a string in Config format

class pzffile.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_metadata(zipf, compress)[source]

Write the metadata

write_files(savedict, *, compress=True, mode='w')[source]

Save a dict to a PZF file

Parameters:

savedict (dict) – Dict with object attributes to store. The keys are subdirectory names in objname:classname format. The values are dicts with the indiviudal filenames as keys and values that are either str, dict or array_like.

save(_camera=False, _canvas=False, _compress=True, _append=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_format(zipf)[source]

Read the format

read_metadata(zipf)[source]

Read the metadata

read_files(files=None)[source]

Read files from a ZipFile

Parameters:

files (list|str, optional) – A list of filenames to read. Default is to read all files. The filenames may contain * and ? wildcards. For convenience, a single string may be specified and will be put in a list. Thus, read_files('F:*') will read all files related to the object named ‘F’.

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

Parameters:

objects (list of str, optional) – A list of specification strings to delimit the objects loaded from the PZF file. Each object spec should be in the format name:class and can contain * and ? wildcards. Thus [ 'F:*', 'M*:Mesh' ] will load the object named ‘F’ and all objects of class Mesh whose name starts with an ‘M’. Default is to load all objects contained in the archive.

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.

version()[source]

Get the version of the PZF format

metadata()[source]

Get metadata from a ZipFile

files()[source]

Return a list with the filenames

objects()[source]

Return a list with the objects stored in the PZF files

extract(path, files=None)[source]

Extract the PzfFile to the give path

Parameters:
  • path (path_like) – Path of the directory where the PZF file should be extracted.

  • files (list of str, optional) – The list of files to extract. Default is to extract all files.

See also

zip

zip the files in a directory into a PZF archive

zip(path, files=None, compress=True)[source]

Zip files from a given path to a PzfFile

Parameters:
  • path (path_like) – Path of a directory with PZF file contents. This will normally be a directory where a PZF file was previously extracted.

  • files (list of str, optional) – The list of files to zip. The file names are relative to path. Default is to zip all files in path.

Note

This can be used in cli mode on an extracted PZF file. For example, if a PZF file was extracted to s folder ‘out’, that folder can be zipped back into a PZF file with the command:

pyformex -c 'PzfFile("new.pzf").zip("out")'

See also

extract

extract the files from a PZF archive

convert(filename=None, compress=None)[source]

Convert a PZF file to the current format.

Parameters:
  • compress (bool, optional) – Specifies whether the converted file should use compression. If not provided, compression will be used if the old file did.

  • filename (str, optional) – Optional name of the output pzf file. This is useful if you want to keep the original file. If not provided, the converted file will replace the original.

  • compress – Specify whether the output pzf should use compression or not. The default is to use compression if the original was compressed.

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.

removeFiles(*files)[source]

Remove selected files from the archive

remove(*objects)[source]

Remove the named objects from the archive

Parameters:

*objects (sequence of str) – One or more strings specifying the objects to be removed from the PZF file. Each object spec should be in the format name:class (as returned by objects()) and can contain * and ? wildcards. Thus remove('F*', '*:Mesh') will remove all objects whose name starts with an F or that are of class Mesh.

read_file(filename)[source]

Return the contents of a text file from the zip archive

39.2. Functions defined in module pzffile

pzffile.convert_files_1_0(tmpdir)[source]

Convert files from 1.0 format to 2.0

pzffile.convert_load_1_0(name, clas, attr, val)[source]

Convert an item from 1.0 format to 2.0

pzffile.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'}
pzffile.load_object(clas, kargs)[source]

Restore an object from the kargs read from file

pzffile.register(clas, name=None)[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.

pzffile.split_format_1_0(contents)[source]

convert old format string into a metadata dict

pzffile.str2dict(s, fmt)[source]

Read a dict from a string representation

Examples

>>> s = "{'a': 0, 'b': (0,1), 'c': 'string'}"
pzffile.zipfile_write_array(zipf, fname, val, datetime=None, compress=True)[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.