[Python] removing excess path data from inside of tar.gz file

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    What specific syntax needs to be changed below in order for the directory structure inside my.tar.gz to begin with the contents of the otherDir directory and NOT with the parents of the otherDir directory?

    PROBLEM DEFINITION:


    1. A text file contains a dynamically-written path to a directory.


    2. The contents of that directory must be archived into a new tar.gz file.


    3. Specifically, the directory whose contents must be archived will have an os-specific path in the form of "C:\path\to\someDir" or "/path/to/someDir", and the path to the directory will be stored in a variable named otherDir.


    4. The CONTENTS of otherDir are what needs to be stored, and NOT the "C:\path\to\someDir" or "/path/to/someDir" .


    5. The problem is that the code below is producing a my.tar.gz whose contents all begin with either "C:\path\to\someDir" or "/path/to/someDir" .


    6. The contents of the resulting my.tar.gz are correct except for the fact that their names begin with an UNWANTED prefix of either "C:\path\to\someDir" or "/path/to/someDir" .


    7. The required solution is that the code below must be changed in order to remove the "C:\path\to\someDir" or "/path/to/someDir" prefix from the name of each member of the resulting my.tar.gz file, while retaining the rest of the data in the my.tar.gz file.

    CODE THAT CAUSES THE PROBLEM:

    Here is the minimal reproducible code-snippet that needs to be changed in order to resolve this OP:

    otherDir = "C:\path\to\someDir" #This is populated dynamically from a text file.
    if os.path.exists(otherDir):
    import tarfile
    EXCLUDE_FILES = ['unwantedSubdirectory']
    tar = tarfile.open("my.tar.gz", "w:gz")
    tar.add(otherDir, filter=lambda x: None if x.name in EXCLUDE_FILES else x)
    tar.close()

    Continue reading...

Compartilhe esta Página