将.tar.gz文件的内容从网站读入python 3.x对象

Chr*_*ris 3 python tar tarfile python-3.x

我是python的新手.在尝试将.tar.gz文件的内容读入python时,我无法弄清楚我做错了什么.我想阅读的tarfile托管在以下网址:

ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/b0/ac/Breast_Cancer_Res_2001_Nov_9_3(1)_61-65.tar.gz

更多关于这个网站的信息(这样你可以信任内容) http://www.pubmedcentral.nih.gov/utils/oa/oa.fcgi?id=PMC13901

tarfile包含期刊文章的.pdf和.nxml副本.还有一些图像文件.

如果我通过复制和粘贴在浏览器中打开文件.我可以保存到我的PC上的某个位置并使用以下命令导入tarfile(注意:当我保存到位置时,winzip将文件从.tar.gz更改为.tar):

import tarfile
thetarfile = "C:/Users/dfcm/Documents/Breast_Cancer_Res_2001_Nov_9_3(1)_61-65.tar"
tfile = tarfile.open(thetarfile)
tfile
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用类似的命令直接访问该文件:

thetarfile = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/b0/ac/Breast_Cancer_Res_2001_Nov_9_3(1)_61-65.tar.gz"
bbb = tarfile.open(thetarfile)
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

 Traceback (most recent call last):
 File "<pyshell#137>", line 1, in <module>
 bbb = tarfile.open(thetarfile)
 File "C:\Python30\lib\tarfile.py", line 1625, in open
 return func(name, "r", fileobj, **kwargs)
 File "C:\Python30\lib\tarfile.py", line 1687, in gzopen
 fileobj = bltn_open(name, mode + "b")
 File "C:\Python30\lib\io.py", line 278, in __new__
 return open(*args, **kwargs)
 File "C:\Python30\lib\io.py", line 222, in open
 closefd)
 File "C:\Python30\lib\io.py", line 615, in __init__
 _fileio._FileIO.__init__(self, name, mode, closefd)
 IOError: [Errno 22] Invalid     argument: 'ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/b0/ac/Breast_Cancer_Res_2001_Nov_9_3(1)_61-65.tar'
Run Code Online (Sandbox Code Playgroud)

在尝试直接从网址读取.tar.gz文件时,有人能解释我做错了什么吗?提前致谢.克里斯

Hel*_*hne 12

不幸的是,您不能只是从网络中打开文件.事情在这里有点复杂.您必须指示解释器创建网络请求并创建表示请求状态的对象.这可以使用该urllib模块完成.

import urllib.request
import tarfile
thetarfile = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/b0/ac/Breast_Cancer_Res_2001_Nov_9_3(1)_61-65.tar.gz"
ftpstream = urllib.request.urlopen(thetarfile)
thetarfile = tarfile.open(fileobj=ftpstream, mode="r|gz")
Run Code Online (Sandbox Code Playgroud)

ftpstream对象类似于文件,表示与ftp服务器的连接.然后tarfile模块可以访问此流.由于我们不传递文件名,因此我们必须在mode参数中指定压缩.