gpt4 book ai didi

python - 想要使用 Python3 从互联网上读取文件的特定偏移量

转载 作者:可可西里 更新时间:2023-11-01 16:30:23 24 4
gpt4 key购买 nike

我想从 python 中的特定偏移量读取 Internet 上的文件。与普通文件处理程序(由 open() 返回)一样,我们有一个 seek() api。从网络读取时有没有办法做到这一点。

import urllib.request
g = urllib.request.urlopen('http://tools.ietf.org/rfc/rfc2822.txt')
g.seek(20)
f=g.read(100)
print(f)

我尝试了以下但它明显给出了错误

io.UnsupportedOperation: seek

我该怎么做才能解决这个问题?

最佳答案

您可以使用 Range header (仅当服务器支持时):

import urllib.request
req = urllib.request.Request('http://tools.ietf.org/rfc/rfc2822.txt',
headers={'Range': 'bytes=20-'})
g = urllib.request.urlopen(req)
f = g.read(100)
print(f)

但并非所有服务器都支持Range。您应该检查响应 header 。如果服务器不支持它,你应该通过读取它们来跳过字节。

import urllib.request
req = urllib.request.Request('http://tools.ietf.org/rfc/rfc2822.txt',
headers={'Range': 'bytes=20-'})
g = urllib.request.urlopen(req)
if 'Content-Range' not in g.info(): # <-----
# OR if g.status != http.client.PARTIAL_CONTENT
g.read(20) # <-----
f = g.read(100)
print(f)

关于python - 想要使用 Python3 从互联网上读取文件的特定偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com