Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] tarfile note update for 3.13 #23

Open
razielanarki opened this issue Nov 29, 2024 · 1 comment · May be fixed by #24
Open

[docs] tarfile note update for 3.13 #23

razielanarki opened this issue Nov 29, 2024 · 1 comment · May be fixed by #24

Comments

@razielanarki
Copy link

razielanarki commented Nov 29, 2024

a pretty straightforward update for the tarfile note:

basically copies the existing built-in methods, but there's room for improvement (mode a?) so i'm posting this as an issue for discussion, rather than a PR:

from tarfile import TarFile, CompressionError, ReadError

class TarZstFile(TarFile):

  OPEN_METH = {
    **TarFile.OPEN_METH,
    'zst': 'zstopen'
  }

  @classmethod
  def zstopen(cls, name, mode='r', fileobj=None, level_or_option=None, zstd_dict=None, **kwargs):
    """Open zstd compressed tar archive name for reading or writing.
       Appending is not allowed.
    """
    if mode not in ("r", "w", "x"):
      raise ValueError("mode must be 'r', 'w' or 'x'")

    try:
      from pyzstd import ZstdFile, ZstdError
    except ImportError:
      raise CompressionError("pyzstd module is not available") from None

    fileobj = ZstdFile(fileobj or name, mode, level_or_option=level_or_option, zstd_dict=zstd_dict)

    try:
      tar = cls.taropen(name, mode, fileobj, **kwargs)
    except (ZstdError, EOFError) as exception:
      fileobj.close()
      if mode == 'r':
        raise ReadError('not a zstd file') from exception
      raise
    except:
      fileobj.close()
      raise

    tar._extfileobj = False
    return tar

usage eg:

with TarZstFile.open('archive.tar.zst', 'r') as tarzst:
  for tarinfo in tarzst:
    print(f'[{tarinfo.name}]')
@Rogdham Rogdham linked a pull request Jan 2, 2025 that will close this issue
@Rogdham
Copy link
Owner

Rogdham commented Jan 2, 2025

Hello @razielanarki and thank you for your report.

I have opened #24 following your suggestion, feel free to tell me what you think.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants