python - 在python的目录中解压.bz2文件
问题描述
我想解压缩一个文件夹中包含的一堆 .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'
为什么我会收到此错误?
解决方案
您必须确保您使用的所有文件路径都存在。最好使用正在打开的文件的完整路径。
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 模块来复制或移动文件。
推荐阅读
- django - 如何在 AWS Elastic Beanstalk 上部署 django 频道 2.x?
- angular - Angular 工作区中 `/apps` 中应用程序的选择器命名约定是什么?
- multithreading - Julia - 读取大文件的并行性
- ruby-on-rails - 我如何在 Rails 中使用子域将用户重定向到他们的域
- html - 如何将内容包装在 div 中?
- spring-integration - 缩放文件轮询器 | 弹簧集成
- c# - 如何在 Pivot Control UWP 上启用拖放
- vue.js - Vuejs多个文件上传一次只上传1个文件
- javascript - React API 错误(未处理的拒绝(TypeError):无法读取未定义的属性“0”)
- node.js - Node.js + Sequelize + SQL Server