Home>

I want to create a TAR.GZ archive with Python with the current directory files, for some exception. The idea is: all selected files are transferred to the Test-V4 directory, and after archiving occurs.


In the Test directory contains the following files:

.
├── 1.
├── 2.
├── 3.
├── BIN.
│ └── TRANSFER.
│ └── .sql
├── .git.
├── .test.

first made it as follows:

#! /usr /bin env python3
Import OS.
Import sys
Import Tarfile
EXCLUDE_FILES= ['./.git', './bin/transfer/.sql',]
DEF FILTER_FUNCTION (Tarinfo):
    If tarinfo.name in explude_files:
        Return none
    ELSE:
        Return Tarinfo.
DEF CREATE_ARCHIVE (PACKAGE, VERSION):
    Archive_Name= Package + "-" + Version + ".tar.gz"
    With tarfile.open (Archive_Name, "W: GZ") AS tar:
        tar.add (".", Filter= Filter_Function)
Create_Archive (package= sys.argv [1], version= sys.argv [2])

Run:

Python test.py Test V4

Get the Test-V4.tar.gz archive and look at the Listing files in the archive:

tar -ztf test-v4.tar.gz
./
./.test.
./one
./2.
./3.
./bin/
./bin/transfer/
./test.py.

Filter works, it would seem -everything is ok. Now I want to place files into the directory. Tarfile has an option for this. ArcName. . Add a parameter:

#! /usr /bin env python3
Import OS.
Import sys.
Import Tarfile
EXCLUDE_FILES= ['./.git', './bin/transfer/.sql']
DEF FILTER_FUNCTION (Tarinfo):
    If tarinfo.name in explude_files:
        Return none
    ELSE:
        Return Tarinfo.
DEF CREATE_ARCHIVE (PACKAGE, VERSION):
    Archive_Name= Package + "-" + Version + ".tar.gz"
    With tarfile.open (Archive_Name, "W: GZ") AS tar:
        tar.add (".", ArcName= Package + "-" + Version, Filter= Filter_Function)
Create_Archive (package= sys.argv [1], version= sys.argv [2])

Run:

Python test.py Test V4

We look again Listing files in the archive:

tar -ztf test-v4.tar.gz
╰─ TAR -ZTF test-v4.tar.gz
Test-V4 /
Test-V4 /.git /
Test-V4 /.test
Test-V4 /1
Test-V4 /2
Test-V4 /3
TEST-V4 /BIN /
TEST-V4 /BIN /TRANSFER /
TEST-V4 /BIN /TRANSFER /.SQL /
Test-V4 /test.py

It can be seen that the filter does not work out when adding ArcName. What am I doing wrong? Tell me, which way to dig?

  • Answer # 1

    paths and names in EXCLUDE_Files. must match paths and names with account ArcName. :

    Def Filter_Function (Tarinfo, ArcName):
        For x in Exclude_Files:
            X= X.Replace ('./', ArcName + '/')
            IF x in tarinfo.name:
                Return none
        Return Tarinfo.
    With tarfile.open (Archive_Name, "W: GZ") AS tar:
        tar.add (".", ArcName= Package + "-" + Version, Filter= Lambda X: Filter_Function (X, ArcName))