0

I need to extract a single file and copy it to some other location using python.

I have this code which does the required thing for gzip compressed data,

tar = tarfile.open(tar_filename)

for member in tar.getmembers():
        if "abc" in member.name:
            member.name = os.path.basename(member.name)
            tar.extract(member, "/tmp/abc")
            return True

I want to do the same thing i.e extract a file in the XZ compressed data. I cant use tarfile.open because it doesn't work. I found that we can open the file using lzma but couldnt find anything helpful that does the similar functionality.

I need to use python 2.7

Do you think we can do the same thing with for xz compressed as well? if not can you suggest me a way to do it.

Thanks

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Red Gundu
  • 183
  • 2
  • 10
  • Does this answer your question? [How to unpack xz file with python which contains only data but no filename?](https://stackoverflow.com/questions/42079724/how-to-unpack-xz-file-with-python-which-contains-only-data-but-no-filename) – mkrieger1 Mar 10 '21 at 22:39
  • hi @mkrieger1, nope my xz file contains so many files in it. I am trying to extract and copy one of the file. Thanks – Red Gundu Mar 10 '21 at 22:41
  • 1
    How about https://stackoverflow.com/questions/17217073/how-to-decompress-a-xz-file-which-has-multiple-folders-files-inside-in-a-singl? Have you tried to use the lzma module? What was the problem? – mkrieger1 Mar 10 '21 at 22:43
  • I wasn't able ro use tar.getmembers() to iterate and find a single file – Red Gundu Mar 10 '21 at 22:51
  • 1
    @RedGundu, can you show us what happens when you _try_? Make sure when you show us the attempt, it includes showing how you opened the file. – Charles Duffy Mar 10 '21 at 22:58
  • That said, note that in general, `tar.xz` doesn't allow random access, so you'll need to read from the front to wherever the file you want to extract is; so even though you're only trying to retrieve one file, it can potentially be quite slow depending on where that file is in the archive. (If that's a dealbreaker, you might think about using `zip` instead in the future, as zip files keep an index showing exactly where each file starts, and has each file in its own separately compressed stream). – Charles Duffy Mar 10 '21 at 23:00
  • Also, 2.7 doesn't have native built-in support for xz, so you'll need to decompress out-of-process. – Charles Duffy Mar 10 '21 at 23:01
  • Are you targeting a system that has the `xz` tool installed? (If so, you can start a `subprocess.Popen` object that runs `xz` to decompress, and attach its stdout to your `tarfile`). – Charles Duffy Mar 10 '21 at 23:03

0 Answers0