【python】tarfile的路徑問題


假設有路徑/home/somebody/test1/test2/test3/

該路徑下有3個文件,a.txt, b.txt, c.txt

 

在目錄/home/somebody下有如下代碼,希望打包a.txt, b.txt, c.txt三個文件

#coding=utf8
import json
import gzip
import msgpackimport tarfile
import os

def test_tar(fname_out, dir_in):
    tar = tarfile.open(fname_out, 'w:gz')
    for root, dir, files in os.walk(dir_in):
        for file in files:
            fullpath = os.joinpath(root, file)
            tar.add(fullpath)
    tar.close()
    os.chdir(cur_path)

if __name__ == "__main__":
    test_tar("test_tar.gz", "test1/test2/test3")

 解壓test_tar.gz結果

test1/test2/test3/a.txt
test1/test2/test3/b.txt
test1/test2/test3/c.txt

問題出現了,解壓后保留了原有的路徑!!可這不是我想要的啊,我只想要三個文件啊!

 

解決辦法:

經測試,壓縮文件的路徑跟tarfile.add()中的路徑完全一致,所以需要在add時把當當前目錄轉換到/home/somebody/test1/test2/test3/,等打包后在把當前目錄還原即可

#coding=utf8
import json
import gzip
import msgpack
import urllib
import urllib2
import tarfile
import os

def test_tar(fname_out, dir_in):
    cur_path = os.getcwd()
    full_fname_out = os.path.join(cur_path, fname_out)
    full_path_in = os.path.join(cur_path, dir_in)
    os.chdir(full_path_in)
    tar = tarfile.open(full_fname_out, 'w:gz')
    for root, dir, files in os.walk(full_path_in):
        for file in files:
            fullpath = file
            tar.add(fullpath, recursive=False)
    tar.close()
    os.chdir(cur_path) if __name__ == "__main__":
    test_tar("test_tar.gz", "test1/test2/test3")

代碼如上所示,關鍵部分加粗顯示了。這樣解壓結果中就沒有復雜的目錄結構了

a.txt
b.txt
c.txt

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM