3

我注意到 tarfile 没有 aw:xz 选项或类似的东西,有没有办法创建 xz 文件?我在 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()
4

1 回答 1

4

Python 3.3 及更高版本具有您正在搜索的选项。

'w:xz' -- 为 lzma 压缩写入打开。

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

对于 3.3 以下的版本,您可以尝试以下方法

  • 假设您在代码的前面为 inputFilename 和 outputFilename 赋值。
  • 请注意,使用with关键字会在执行缩进代码后自动关闭文件

示例代码:

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)

我搜索了其他答案,发现一个条目提到了将 lzma 导入 python 2.7 的问题。此条目中提供了您可以遵循的解决方法。

这是链接 - Python 2.7:使用“lzma”模块压缩 XZ 格式的数据

于 2015-04-05T02:26:38.973 回答