/usr/lib/python3/dist-packages/zict/file.py is in python3-zict 0.1.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | from __future__ import absolute_import, division, print_function
import errno
import os
try:
from urllib.parse import quote, unquote
except ImportError:
from urllib import quote, unquote
from .common import ZictBase
def _safe_key(key):
"""
Escape key so as to be usable on all filesystems.
"""
# Even directory separators are unsafe.
return quote(key, safe='')
def _unsafe_key(key):
"""
Undo the escaping done by _safe_key().
"""
return unquote(key)
class File(ZictBase):
""" Mutable Mapping interface to a directory
Keys must be strings, values must be bytes
Note this shouldn't be used for interprocess persistence, as keys
are cached in memory.
Parameters
----------
directory: string
mode: string, ('r', 'w', 'a'), defaults to 'a'
Examples
--------
>>> z = File('myfile') # doctest: +SKIP
>>> z['x'] = b'123' # doctest: +SKIP
>>> z['x'] # doctest: +SKIP
b'123'
Also supports writing lists of bytes objects
>>> z['y'] = [b'123', b'4567'] # doctest: +SKIP
>>> z['y'] # doctest: +SKIP
b'1234567'
Or anything that can be used with file.write, like a memoryview
>>> z['data'] = np.ones(5).data # doctest: +SKIP
"""
def __init__(self, directory, mode='a'):
self.directory = directory
self.mode = mode
self._keys = set()
if not os.path.exists(self.directory):
os.mkdir(self.directory)
else:
for n in os.listdir(self.directory):
self._keys.add(_unsafe_key(n))
def __str__(self):
return '<File: %s, mode="%s", %d elements>' % (self.directory, self.mode, len(self))
__repr__ = __str__
def __getitem__(self, key):
if key not in self._keys:
raise KeyError(key)
with open(os.path.join(self.directory, _safe_key(key)), 'rb') as f:
return f.read()
def __setitem__(self, key, value):
with open(os.path.join(self.directory, _safe_key(key)), 'wb') as f:
if isinstance(value, (tuple, list)):
for v in value:
f.write(v)
else:
f.write(value)
self._keys.add(key)
def __contains__(self, key):
return key in self._keys
def keys(self):
return iter(self._keys)
__iter__ = keys
def __delitem__(self, key):
if key not in self._keys:
raise KeyError(key)
os.remove(os.path.join(self.directory, _safe_key(key)))
self._keys.remove(key)
def __len__(self):
return len(self._keys)
|