Search code examples
pythoncompressiontarfile

Tarfile create xz file


i have noticed that tarfile doesn't have a w:xz option or something similar,is there any way to create a xz file?i have this code in python

dir=tkFileDialog.askdirectory(initialdir="/home/david")
        if x.get()=="gz":
            tar = tarfile.open(dir+".tar.gz", "w:gz")
            tar
            for i in range(lbox.size()):
                tar.add(e1.get()+"/"+lbox.get(i),arcname=lbox.get(i))
            tar.close()
        if x.get()=="bz":
            tar = tarfile.open(dir+".tar.gz", "w:bz2")
            tar
            for i in range(lbox.size()):
                tar.add(e1.get()+"/"+lbox.get(i),arcname=lbox.get(i))
            tar.close()
        if x.get()=="xz":
            tar = tarfile.open(dir+".tar.gz", "w:gz")
            tar
            for i in range(lbox.size()):
                tar.add(e1.get()+"/"+lbox.get(i),arcname=lbox.get(i))
            tar.close()

Solution

  • Python version 3.3 and above have the option for which you are searching.

    'w:xz' -- Open for lzma compressed writing.

    https://docs.python.org/3.3/library/tarfile.html

    For versions below 3.3 you may be able to try the following

    • Assume you assign values to inputFilename and outputFilename earlier in your code.
    • Note that using the with keyword automatically closes the file after the indented code is executed

    Sample Code:

    import lzma 
    
    # open input file as binary and read input data
    with open(inputFilename, 'rb') as iFile:
        iData = iFile.read()
    
    # compress data
    oData = lzma.compress(iData)
    
    # open output file as binary and write compressed data
    with open(outputFilename, 'wb') as oFile:
        oFile.write(oData)
    

    I searched for other answers and I found an entry that mentioned problems with importing lzma into python 2.7. A workaround is presented in this entry that you could follow.

    Here is the link - Python 2.7: Compressing data with the XZ format using the "lzma" module