1

我有 30,000 个文件夹,每个文件夹包含 5 个 bz2 的 json 数据文件。

我正在尝试使用 os.walk() 循环遍历文件路径并解压缩每个压缩文件并保存在原始目录中。

import os
import bz2

path = "/Users/mac/PycharmProjects/OSwalk/Data"
for(dirpath,dirnames,files) in os.walk(path):

for filename in files:
    filepath = os.path.join(dirpath , filename)
     newfilepath = os.path.join(dirpath , filename + '.decompressed')

        with open(newfilepath , 'wb') as new_file , 
          bz2.BZ2File(filepath , 'rb') as file:

              for data in iter(lambda: file.read(100 * 1024) , b''):
                  new_file.write(data)

运行代码时出现以下错误。

File 
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_compr 
ession.py", line 103, in read
data = self._decompressor.decompress(rawblock, size)
OSError: Invalid data stream

我已经读到使用解压器方法在 mac 上运行代码可能会出现问题,或者我是否遗漏了其他东西?

4

1 回答 1

0

看起来您可能正在尝试解压缩已经解压缩的结果。你应该过滤掉它们。

import os
import bz2

path = "/Users/mac/PycharmProjects/OSwalk/Data"
for (dirpath, dirnames, files) in os.walk(path):
    for filename in files:
        # filter out decompressed files
        if filename.endswith('.decompressed'):
            continue

        filepath = os.path.join(dirpath, filename)
        newfilepath = os.path.join(dirpath, filename + '.decompressed')

        with open(newfilepath, 'wb') as new_file,
            bz2.BZ2File(filepath, 'rb') as file:

            for data in iter(lambda: file.read(100 * 1024), b''):
                new_file.write(data)
于 2017-12-07T23:16:01.053 回答