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


as opposed to just (what I want)


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?


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


$ rar a -ep1 test.rar data

The piece of rar help:

  ep            Exclude paths from names
  ep1           Exclude base directory from names
  • Thank you for the alternatives. I am running 7z through subprocess in python, so I am wary of changing directory. – paragbaxi Feb 18 '11 at 14:57

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 = [
output = subprocess.check_output(args, cwd = 'data').decode("utf-8")

what dr01 answered is generally correct, but why use 7z for compressing a single file at all?

I'd suggest you take a look at xz or maybe even pxz, if that's available on your distro. xz works well with tar, newer versions of tar have the "-J" switch, which runs it through xz

In any event, you can use xz to compress a single file, just as you'd use gzip or bzip2:

$ xz file.txt

(creates file file.txt.xz)

  • Is xz or pxz compatible with 7zip? My target audience is windows users and I hope to achieve compatibility with decent compression. – paragbaxi Mar 22 '11 at 20:05
  • 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. – polemon Mar 22 '11 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.