Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python urllib2下载的.torrent文件无法在bittorrent客户端中打开_Python_Gzip_Urllib2_Bittorrent - Fatal编程技术网

使用python urllib2下载的.torrent文件无法在bittorrent客户端中打开

使用python urllib2下载的.torrent文件无法在bittorrent客户端中打开,python,gzip,urllib2,bittorrent,Python,Gzip,Urllib2,Bittorrent,我正在使用此代码下载.torrent文件: torrent = urllib2.urlopen(torrent URL, timeout = 30) output = open('mytorrent.torrent', 'wb') output.write(torrent.read()) 生成的mytorrent.torrent文件不会在任何bittorrent客户端中打开,并引发“无法解析元文件”错误。问题显然是,尽管torrent URL(例如)以“.torrent”后缀结尾,但它是使用g

我正在使用此代码下载.torrent文件:

torrent = urllib2.urlopen(torrent URL, timeout = 30)
output = open('mytorrent.torrent', 'wb')
output.write(torrent.read())
生成的mytorrent.torrent文件不会在任何bittorrent客户端中打开,并引发“无法解析元文件”错误。问题显然是,尽管torrent URL(例如)以“.torrent”后缀结尾,但它是使用gzip压缩的,需要解压缩,然后保存为torrent文件。我在terminal:
gunzip mytorrent.torrent>test.torrent
中解压文件,并在bittorrent客户端打开该文件,该客户端可以正常打开


如何修改python以查找文件编码并确定文件是如何压缩的,如何使用正确的工具将其解压缩并另存为.torrent文件?

gzip'ed数据必须解压缩。如果您注意内容编码头,您可以详细说明这一点

import gzip, urllib2, StringIO

req = urllib2.Request(url)
opener = urllib2.build_opener()
response = opener.open(req)
data = response.read()
if response.info()['content-encoding'] == 'gzip':
    gzipper = gzip.GzipFile(StringIO(fileobj=data))
    plain = gzipper.read()
    data = plain
output.write(data)
Traceback(最后一次调用):文件“unzip_torrent.py”,第16行,在plain=gzipper.read()文件“/usr/lib/python2.7/gzip.py”,第249行,在read self._read(readsize)文件“/usr/lib/python2.7/gzip.py”,第283行,在_readpos=self.fileobj.tell()中#保存当前位置属性错误:“str”对象没有属性“tell”