【问题标题】:Decompressing .bz2 files in a directory in python在python中解压缩目录中的.bz2文件
【发布时间】:2021-06-01 08:20:58
【问题描述】:

我想解压缩一个文件夹中包含的一堆 .bz2 文件(其中还有 .zst 文件)。我正在做的事情如下:

 destination_folder = "/destination_folder_path/"

 compressed_files_path="/compressedfiles_folder_path/"

 dirListing = os.listdir(compressed_files_path)

 for file in dirListing:

     if ".bz2" in file:

        unpackedfile = bz2.BZ2File(file)
        data = unpackedfile.read()
        open(destination_folder, 'wb').write(data)

但我不断收到以下错误消息:

Traceback (most recent call last):
  File "mycode.py", line 34, in <module>
    unpackedfile = bz2.BZ2File(file)
  File ".../miniconda3/lib/python3.9/bz2.py", line 85, in __init__
    self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'filename.bz2'

为什么我会收到此错误?

【问题讨论】:

  • _builtin_open(filename, mode) in bz2.py 需要一个完整的文件路径。你向这个函数传递了什么?
  • 您好,感谢您的快速回复!所以在这里我传递“打开”目标文件夹的完整路径,确实是上面定义的“destination_folder”。
  • 如果您的 bz2 文件与使用它们的 Python 脚本位于同一目录中,您可以简单地使用 bz2.open("filename.bz2")。如果你的compressed_files_path和你的脚本目录不一样,需要使用文件的完整路径。

标签: python compression


【解决方案1】:

您必须确保您使用的所有文件路径都存在。 最好使用正在打开的文件的完整路径。


import os
import bz2


# this path must exist
destination_folder = "/full_path_to/folder/"

compressed_files_path = "/full_path_to_other/folder/"

# get list with filenames (strings)
dirListing = os.listdir(compressed_files_path)

for file in dirListing:
    # ^ this is only filename.ext
    if ".bz2" in file:
        
        # concatenation of directory path and filename.bz2
        existing_file_path = os.path.join(compressed_files_path, file)

        # read the file as you want
        unpackedfile = bz2.BZ2File(existing_file_path)
        data = unpackedfile.read()

        new_file_path = os.path.join(destination_folder, file)
        with bz2.open(new_file_path, 'wb') as f:
            f.write(data)

您还可以使用 shutil 模块来复制或移动文件。

os.path.exists

os.path.join

shutil

bz2 examples

【讨论】:

  • 很好,成功了,非常感谢!所以基本上问题是路径名?不过这很奇怪,因为我确信它是完整且正确的路径。另一个后续问题:我正在尝试在同一个文件夹中解压缩其中的 .zst 文件。我可以像使用“bz2.BZ2File”一样简单天真地使用这个函数“zstandard.ZstdDecompressor()”还是比这更复杂?再次提前感谢您的帮助!
  • 在您的示例代码中,读取数据后,您正试图打开文件夹 - open(destination_folder, 'wb')open() 函数用于打开文件。目前尚不完全清楚您到底想对数据做什么。在我的示例中,我只是将数据从一个 bz2 文件保存到另一个文件夹中的另一个 bz2 文件。这行得通,但如果你想要不同的结果,请重写这部分。关于 zstandard,我无话可说。貌似是需要安装的第三方库。
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多