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

今天小編就爲大家分享一篇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>

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

以上這篇python 實現將文件或文件夾用相對路徑打包爲 tar.gz 文件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。

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