7z command line add file to a flat directory 7z file

5,006

Solution 1

Figured out an alternative that works for me. I am utilizing subprocess to call 7z. The cwd attribute changes the working directory for the subprocess command. The code below solves my example above, where 'data' is the path that I would like to add a file from.

args = [
        '7z',
        'a',
        filename_7z,
        filename,
        ]
output = subprocess.check_output(args, cwd = 'data').decode("utf-8")

Solution 2

One of possible solutions is to chdir to some directory before compressing. For example:

$ cd data; 7z a ../test.7z *
$ 7z l ../test.7z
...

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2011-02-18 15:29:53 ....A            6           11  x.txt
------------------- ----- ------------ ------------  ------------------------
...

Yet another way is using another archiver, e.g. rar. It has a lot of useful command line swithes. Your problem can be solved with -ep/-ep1 options:

$ rar a -ep test.rar data

or

$ rar a -ep1 test.rar data

The piece of rar help:

  ep            Exclude paths from names
  ep1           Exclude base directory from names
Share:
5,006

Related videos on Youtube

paragbaxi
Author by

paragbaxi

Updated on September 18, 2022

Comments

  • paragbaxi
    paragbaxi almost 2 years

    I would like to compress file "./data/x.txt" to path "./data/x.7z".

    When running

    7z a ./data/x.txt.7z ./data/x.txt
    

    The file "./data/x.txt" holds

    data/x.txt
    

    as opposed to just (what I want)

    x.txt
    

    However, I would like 7z to ignore the path "./data" directory inside of the x.7z file. To clarify, I would like 7z to flatten the directory structure in the 7z file when adding x.txt.

    Is this possible?

  • paragbaxi
    paragbaxi over 13 years
    Is xz or pxz compatible with 7zip? My target audience is windows users and I hope to achieve compatibility with decent compression.
  • polemon
    polemon over 13 years
    That depends on the archiving program that the user uses. In case you want to distribute files, that are for users that potentially don't have any archiving programs, I'd consider using SFX. 7z can do that. xz uses the same compression algorithm, things like peazip can handle .xz files.