Python: Extracting specific files with pattern from tar.gz without extracting the complete file

后端 未结 2 1523
梦如初夏
梦如初夏 2021-01-20 11:47

I want to extract all files with the pattern *_sl_H* from many tar.gz files, without extracting all files from the archives.

I found these lines, but it

2条回答
  •  礼貌的吻别
    2021-01-20 12:41

    Take a look at TarFile.getmembers() method which returns the members of the archive as a list. After you have this list, you can decide with a condition which file is going to be extracted.

    import tarfile
    import os
    
    os.mkdir('outdir')
    t = tarfile.open('example.tar', 'r')
    for member in t.getmembers():
        if "_sl_H" in member.name:
            t.extract(member, "outdir")
    
    print os.listdir('outdir')
    

提交回复
热议问题