簡體   English   中英

如何僅使用Python將tar文件轉換為tar.gz?

[英]How to convert tar file to tar.gz using Python only?

我正在尋找如何僅使用Python代碼將tar文件轉換為tar.gz? 我已經嘗試過很多問題,但沒有任何效果
https://docs.python.org/3.6/library/tarfile.html
https://docs.python.org/3.6/library/gzip.html


我得到不同的錯誤:

  • 使用gzip.open,他創建了一個帶有“ tar”的“ gz”文件
  • import gzip
    
    tarfile = "/home/user/file.tar"
    with open(tarfile, 'rb') as f_in:
        with gzip.open(tarfile+'.gz', 'wb') as f_out:
            f_out.writelines(f_in)
    

  • 使用copy.deepcopy + gzip壓縮,我具有帶有Deepcopy功能的'TextIOWrapper'或'BufferedReader'
  • import gzip, copy
    tarfile = "/home/user/file.tar"
    
    with open(tarfile, 'rb') as f_in:
        data = copy.deepcopy(f_in)
    with open(tarfile+'.gz', 'wb') as f_out:
            try:
                gdata = gzip.compress(data)
                f_out.write(gdata)
            except Exception as e:
                print("error: %s" % (e))
    

  • gzip.compress +寫,我有“ BufferedReader”
  • import gzip
    
    tarfile = "/home/user/file.tar"
    with open(tarfile, 'rb') as f_in:   
        with open(tarfile+'.gz', 'wb') as f_out:
            try:
                data = gzip.compress(f_in)
                f_out.write(data)
            except Exception as e:
                print("error: %s" % (e))
    

    所以,我需要幫助。

    我認為最簡單的方法是將tar文件提取到一個臨時目錄,然后將其重新壓縮為tar.gz

    import tarfile, shutil
    
    TARFILE = "/home/user/file.tar"
    TMP_DIR = ".tar_gz_converter_tmp"
    
    with tarfile.open(TARFILE ) as f:
        f.extractall(TMP_DIR)
    
    with tarfile.open(TARFILE + ".gz", "w:gz") as f:
        f.add(TMP_DIR, ".")
    
    shutil.rmtree(TMP_DIR)
    

    請注意,如果將模式設置為w:gz那么tarfile如何將文件壓縮為tar.gz 也可以在內存中進行轉換,但是肯定要復雜得多。

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM