简体   繁体   中英

Creating tar file in Python with tarfile makes directory tree inside of tar.gz

For creating tar.gz file I use the below code.

import os
import tarfile
def tardir(path, tar_name):
    with tarfile.open(tar_name, "w:gz") as tar_handle:
        for root, dirs, files in os.walk(path):
            for file in files:
                tar_handle.add(os.path.join(root, file))
tardir('C:/../../projects/project_folder', 'C:/../../projects/project_folder/tar_files/tar_file.tar.gz')
tar.close()

I want gzip the tar_files folder and when i unzip it I only want to see this folder. But with the above code, inside of tar file I see it stores with directory tree. Like when I open it i see the below folders

/../../projects/project_folder

How can i solve this problem? Thanks for answering

Below code from below link solves my question.

How to create full compressed tar file using Python?

import tarfile
import os.path

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

Giving absolute address to the params output_filename and source_dir works appropriate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM