Search code examples
pythondirectorytartarfile

Add files to empty directory within Tar in Python


In Python, I am trying to create a tar with two empty directories in it, and then add a list of files to each empty directory within the tar. I have tried doing it this way below, but It does not work.

def ISIP_tar_files():
    with tarfile.open("eeg_files.tar", "w") as f:
        ep_dir = tarfile.TarInfo("Eplilepsy Reports")
    not_ep_dir = tarfile.TarInfo("Non Epilepsy Reports")
        ep_dir.type = not_ep_dir.type = tarfile.DIRTYPE
    f.addfile(ep_dir)
    f.addfile(not_ep_dir)
    with ep_dir.open():
            for name in ep_list:
        f.tarfile.add(name)

I honestly did not believe it would work, but it was worth a try because I couldn't find any other solutions on Google. This is just one module of the code, and it does not include the main program or imports. ep_list is a list of files with paths, it looks similar to:

ep_list = [/data/foo/bar/file.txt, /data/foo/bar2/file2.txt, ...]

Any Sugegstions?


Solution

  • import tarfile
    import os
    
    ep_list = ['./foo/bar/file.txt', './foo/bar/file2.txt']
    
    def ISIP_tar_files():
        with tarfile.open("eeg_files.tar", "w") as f:
            ep_dir = tarfile.TarInfo("Eplilepsy Reports")
            not_ep_dir = tarfile.TarInfo("Non Epilepsy Reports")
            ep_dir.type = not_ep_dir.type = tarfile.DIRTYPE
            ep_dir.mode = not_ep_dir.mode = 0o777
            f.addfile(ep_dir)
            f.addfile(not_ep_dir)
            for name in ep_list:
                f.add(name, arcname="Eplilepsy Reports/" + os.path.basename(name), recursive=False)
    

    The directory file permission mode should be made executable at least for the owner. Otherwise it cannot be extracted.

    • arcname is the alternative name for the file in the archive.
    • recursive means whether or not keep the original directories added recursively, its default value is True.