def open(self, basefile, maindir, suffix, mode="r", version=None, attachment=None): """ Context manager that opens files for reading or writing. The parameters are the same as for :meth:`~ferenda.DocumentStore.path`, and the note is applicable here as well -- use :meth:`~ferenda.DocumentStore.open_downloaded`, :meth:`~ferenda.DocumentStore.open_parsed` et al if possible. Example: >>> store = DocumentStore(datadir="/tmp/base") >>> with store.open('123/a', 'parsed', '.xhtml', mode="w") as fp: ... res = fp.write("hello world") >>> os.path.exists("/tmp/base/parsed/123/a.xhtml") True """ filename = self.path(basefile, maindir, suffix, version, attachment) fp = NamedTemporaryFile(mode, delete=False) fp.realname = filename try: yield fp finally: tempname = fp.name fp.close() if not os.path.exists(filename) or not filecmp.cmp(tempname, filename): util.ensure_dir(filename) shutil.move(tempname, filename) else: os.unlink(tempname)
def _open(self, filename, mode): if "w" in mode: fp = NamedTemporaryFile(mode, delete=False) fp.realname = filename try: yield fp finally: tempname = fp.name fp.close() if not os.path.exists(filename) or not filecmp.cmp(tempname, filename): util.ensure_dir(filename) shutil.move(tempname, filename) else: os.unlink(tempname) else: if "a" in mode and not os.path.exists(filename): util.ensure_dir(filename) fp = open(filename, mode) yield fp