python 實現將文件或文件夾用相對路徑打包爲 tar.gz 文件

默認情況下,tarfile 打包成的 tar.gz 文件會帶絕對路徑,而很多情況下,我們需要的是相對打包文件夾的路徑。

代碼:

<pre name="code" class="python"><span style="font-size:18px;">import tarfile
tmp_tar_dir = "/home"
file_name = "test.tar.gz"
tmp_dir = "/home/centos"
soft_name = "php"
tar = tarfile.open(os.path.join(tmp_tar_dir,file_name),"w:gz")
for root,dir,files in os.walk(os.path.join(tmp_dir,soft_name)):
    root_ = os.path.relpath(root,start=tmp_dir)
    #tar.add(root,arcname=root_)
    for file in files:
        full_path = os.path.join(root,file)
        tar.add(full_path,arcname=os.path.join(root_,file))
tar.close()</span>



注意:打包出來的文件,如果原目錄總存在空文件夾,則打包出來的文件中不包含此空文件夾。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章