• Ian Stuart's picture

    Adding a text-string as a file to a gzip'd file

    Ian Stuart / March 27, 2019
  • I had reason to add a timestamp file to an archive - a nice simple file, with the time of creating as a single line, so nothing complicated..... but this is python, and there are more solutions out there than I've had hot dinners (well, maybe not - but certainly more than I've had Vindaloo curries.)

    None of them worked for me.

    I don't think that my archive was an in-memory "file"

    This does:

        # The submitted files have a timestamp.txt file with them.
        def tar_source(self, path):
            import tarfile
            import time
            from contextlib import closing
            from datetime import datetime
            timestamp = datetime.now().strftime(self.timestamp_format)
            tar_file = io.BytesIO()
            with tarfile.open(fileobj=tar_file, mode="w:gz") as tar_handle:
                tar_handle.add(path, arcname=".")
                with closing(io.BytesIO(timestamp.encode())) as fobj:
                    tarinfo = tarfile.TarInfo('timestamp.txt')
                    tarinfo.size = len(fobj.getvalue())
                    tarinfo.mtime = time.time()
                    tar_handle.addfile(tarinfo, fileobj=fobj)
            return tar_file.read()