有没有办法在线从 tar.gz 文件中读取数据而无需在本地下载它们?

Is there any way to read data from tar.gz files online without downloading them locally?

提问人:Imtiaz Nabi 提问时间:11/9/2023 最后编辑:snakecharmerbImtiaz Nabi 更新时间:11/9/2023 访问量:39

问:

因此,我正在做一个需要来自宇宙2号卫星的特定数据的项目。

数据存储在压缩的tar.gz中,并且有数千个文件,因此由于时间和存储限制,我不想将它们全部下载然后一一处理。

相反,我想寻找一种替代方法,允许我直接从文件中读取数据,而无需先下载它们。

也许请求或 urllib 可以做到这一点

目前我尝试了

url = https://sitename.com/data.tar.gz

文件 = response.get(url, stream= True)

使用 tarfile.open(file, “r:gz”) 作为 f: f.extractall()

python 请求 gzip tarfile

评论

1赞 juanpa.arrivillaga 11/9/2023
“无需先下载它们”是什么意思?你的意思是没有将它们全部保存在磁盘上?你不能只在磁盘上保存一个,删除它,然后继续下一个吗?
0赞 Michael Butscher 11/9/2023
您必须下载并解压缩从 tar.gz 文件开头到 tar.gz 中所需文件结尾的所有内容,但您不必存储数据中无趣的部分。

答:

0赞 Akshat Pande 11/9/2023 #1

我查找了几个选项,找到了这个 - https://extract.me/

您可以直接使用网址,因此只需右键单击ftp文件的链接,然后复制并粘贴即可进行检查。

希望对您有所帮助

评论

0赞 Community 11/9/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。
1赞 Md Irshad Sheikh 11/9/2023 #2

您可以通过使用 urllib 模块获取文件和 tarfile 模块提取其内容,从 tar.gz 文件中在线读取数据,而无需在 Python 中本地下载它。

下面是如何执行此操作的示例:

import urllib.request
import tarfile
import io

url = "http://example.com/your_file.tar.gz"  # Replace with the actual URL of the tar.gz file

# Fetch the tar.gz file
response = urllib.request.urlopen(url)
tar_bytes = io.BytesIO(response.read())

# Extract the contents
with tarfile.open(fileobj=tar_bytes, mode="r:gz") as tar:
    for member in tar.getmembers():
        f = tar.extractfile(member)
        if f is not None:
            content = f.read()
            print(content.decode("utf-8"))