当前位置: 代码迷 >> 综合 >> python3.6读取tar.bz2文件
  详细解决方案

python3.6读取tar.bz2文件

热度:102   发布时间:2023-10-26 00:04:31.0

0.环境

ubuntu16.04
python3.6
tarfile

1.问题

tarfile.ReadError: not a bzip2 file

File "/usr/lib/python3.6/tarfile.py", line 1678, in bz2openraise ReadError("not a bzip2 file")
tarfile.ReadError: not a bzip2 file

2.解决

改:
tar = tarfile.open(tar_path, "r:bz2")
为:
tar = tarfile.open(tar_path, "r")

3.完整代码

import tarfile
def extract(tar_path, target_path):"""Args:tar_path: tar file local path(Both relative path and absolute path can be used)target_path: the path you want to save your file"""try:tar = tarfile.open(tar_path, "r")tar.debug = 1file_names = tar.getnames()for file_name in file_names:if not file_name.endswith(".jpg"):continue# print(file_name)tar.extract(file_name, target_path)tar.close()except Exception as e:print(e)raise