使用tarfile打开.tgz文件时出现ReadError报错求助
解决tar.gz文件提取时的ReadError问题
你的代码与报错信息
代码:
tar_path = os.path.join("datasets/housing/housing.tgz") tgz_open = tarfile.open(tar_path,'r') tgz_open.extract(tgz_open,"datasets/housing") tgz_open.close()
报错:
--------------------------------------------------------------------------- ReadError Traceback (most recent call last) Input In [24], in <module> 1 tar_path = os.path.join("datasets/housing/housing.tgz") ----> 2 tgz_open = tarfile.open(tar_path,'r') 4 tgz_open.extract(tgz_open,"datasets/housing") 5 tgz_open.close() File ~\Anaconda3\lib\tarfile.py:1616, in TarFile.open(cls, name, mode, fileobj, bufsize, **kwargs) 1614 fileobj.seek(saved_pos) 1615 continue -> 1616 raise ReadError("file could not be opened successfully") 1618 elif ":" in mode: 1619 filemode, comptype = mode.split(":", 1) ReadError: file could not be opened successfully
解决方案
验证文件路径与完整性
- 先确认文件路径是否正确:执行
print(os.path.exists(tar_path)),如果返回False,说明路径错误或者文件不存在,检查目录结构、文件名拼写。 - 手动用系统解压工具打开
housing.tgz,如果打不开,说明文件损坏,重新下载。
- 先确认文件路径是否正确:执行
修正tarfile打开模式
仅用'r'模式无法正确识别gzip压缩的tar包,需指定压缩格式:# 明确指定gzip格式 tgz_open = tarfile.open(tar_path, 'r:gz') # 或者让tarfile自动识别压缩格式 # tgz_open = tarfile.open(tar_path, 'r:*')修复extract方法的参数错误
你错误地将TarFile对象传入extract方法,该方法需要的是要提取的文件名或TarInfo对象。如果要提取所有文件,使用extractall():# 提取所有文件到目标目录 tgz_open.extractall("datasets/housing") # 若仅提取单个文件,例如housing.csv: # tgz_open.extract("housing.csv", "datasets/housing")使用上下文管理器优化代码
用with语句自动管理文件生命周期,避免手动关闭的繁琐与异常风险:import os import tarfile tar_path = os.path.join("datasets/housing/housing.tgz") if os.path.exists(tar_path): with tarfile.open(tar_path, 'r:gz') as tgz_open: tgz_open.extractall("datasets/housing") else: print(f"错误:文件不存在 -> {tar_path}")
内容的提问来源于stack exchange,提问作者Dhinesh Mathiyalagan
相关产品推荐
相关产品推荐

