python - tar 文件无法打开 tgz

标签 python urllib os.path tarfile

我正在尝试从此网站下载 tgz 文件: https://plg.uwaterloo.ca/cgi-bin/cgiwrap/gvcormac/foo07

这是我的脚本:

import os
from six.moves import urllib
import tarfile

spam_path=os.path.join('ML', 'spam')
root_download='https://plg.uwaterloo.ca/cgi-bin/cgiwrap/gvcormac/foo07'
spam_url=root_download+'255 MB Corpus (trec07p.tgz)'

if not os.path.isdir(spam_path):
    os.makedirs(spam_path)

path=os.path.join(spam_path, 'trec07p.tgz')
if not os.path.isfile('trec07p.tgz'):
    urllib.request.urlretrieve(spam_url,path)
tar_file=tarfile.open(path)

我不确定我缺少什么,但返回以下错误:

---------------------------------------------------------------------------
ReadError                                 Traceback (most recent call last)
<ipython-input-21-5644813e0670> in <module>()
     18 if not os.path.isfile('trec07p.tgz'):
     19     urllib.request.urlretrieve(spam_url,path)
---> 20 tar_file=tarfile.open(path)
     21 # tar_file.extractall(path)
     22 # tar_file.close()

/anaconda/lib/python2.7/tarfile.pyc in open(cls, name, mode, fileobj, bufsize, **kwargs)
   1678                         fileobj.seek(saved_pos)
   1679                     continue
-> 1680             raise ReadError("file could not be opened successfully")
   1681 
   1682         elif ":" in mode:

ReadError: file could not be opened successfully

预先感谢您的帮助!

最佳答案

您可以将其他参数添加到 tarfile.open 。您需要将模式设置为'r:gz'

tarfile.open(path, 'r:gz')

接受协议(protocol)后的工作示例:

import tarfile

import requests

URL = 'https://plg.uwaterloo.ca/cgi-bin/cgiwrap/gvcormac/trec07p.tgz'
FILE = '/home/blake/Downloads/trec07p.tgz'

resp = requests.get(URL, stream=True)
resp.raise_for_status()

with open(FILE, 'wb') as out_file:
    for line in resp.iter_content(chunk_size=1024*4, decode_unicode=False):
        out_file.write(line)


f = tarfile.open(FILE, 'r:gz')
print(f.getnames())

f.close()

输出:

['trec07p/data/inmail.35059',
 'trec07p/data/inmail.34430',
 'trec07p/data/inmail.45722',
 ..
 ..]

关于python - tar 文件无法打开 tgz,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46651490/

相关文章:

python - 将 timedelta 对象转换为时间对象

python - 使用 requests 模块正确分配 cookie

python - 从嵌套的 span 标签获取数据

python - 使用 os.path.isdir() 时 './' 和 '../' 有什么区别?

python - 从 python 脚本更改目录 : how to not open a new shell

python - os.path.join 失败,显示 "TypeError: object of type ' LocalPath' has no len()"

python - 使用 Python 在 Facebook 粉丝页面上发布

python - 修复列表中损坏的 html 元素

Python同步urllib2结果

python - 尝试使用 Python 从一系列 URL 下载数据(文本)