pythontartarfile

Python tarfile creates subfolders in a tar


I need to make a tar from files in the directory Here is my code

import tarfile
import os

path = '/home/atom/Desktop/test_arch/sample.tar'
source = '/home/atom/Desktop/test_arch'
files = os.listdir(source)
files.sort()

tar = tarfile.open(path, "w")
for file in files:
    print(file)
    file_path = source + '/' + file
    tar.add(file_path)
tar.close()

Everything works fine. The archive is created. But instead of a list of files in it. I got several subsolders:

/home/atom/Desktop/test_arch

And only in the last subfolder are my files

If I try:

tar.add(file)

It gives an Error:

FileNotFoundError: [Errno 2] No such file or directory: '1.jpg'

Solution

  • You should change Current Working Directory to work directly in directory source
    and then you can use filename without source/ and archive will keep it without source/.

    import tarfile
    import os
    
    source = '/home/atom/Desktop/test_arch'
    path = os.path.join(source, 'sample.tar')
    
    # --- keep current directory and go to source directory
    
    old_dir = os.getcwd()
    
    os.chdir(source)   # change directory
    
    # --- compress using only names (or relative paths)
    
    files = sorted(os.listdir())
    
    tar = tarfile.open(path, "w")
    
    for filename in files:
        print(filename)
        if filename != 'sample.tar':
            tar.add(filename)
    
    tar.close()
    
    # --- go back to previuos directory
    
    os.chdir(old_dir)