通过pycdf读取zip文件对象而不解压缩

2024-05-15 02:09:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何在zip文件中打开文件而不解压缩。具体做法如下:

import zipfile
archive = zipfile.ZipFile(path_to_zipfile, 'r')
my_zipfile = archive.open('file_01.cdf')    # "file_01.cdf" is contained in the zipfile

我的问题是:zip文件中包含的文件“file01.cdf”是cdf格式的。通常,CDF格式文件的读取方式如下:

from spacepy import pycdf

cdf_file = pycdf.CDF(path_to_file)
data = cdf_file.copy()

问题是:函数pycdf.CDF接受字符串格式的参数。但是,我想将zipfile对象作为参数传递给pycdf.CDF函数。(因为我没有解压zip文件,所以我没有字符串形式的文件路径)。有什么办法克服这个问题吗?非常感谢你!你知道吗


Tags: 文件topath函数字符串import格式zip
1条回答
网友
1楼 · 发布于 2024-05-15 02:09:47

我知道你明确要求不解压,但我认为这是不可能的(有人会纠正我,如果我错了,我希望)。你知道吗

你可以这样做:

import zipfile
import os
import tempfile
import shutil

path = r'C:\Users\XXX\Desktop\test.zip' # my zip file
archive = zipfile.ZipFile(path, 'r')

tmpdir = tempfile.mkdtemp(dir=os.getcwd()) # create a temp folder in the working directory
archive.extract('test.txt', path=tmpdir) # extract your file to the temp folder
path_to_my_file = os.path.join(tmpdir, 'test.txt') # this is the path to the extracted file
#    -
# do stuff with your file path
#    -
print(path_to_my_file)
shutil.rmtree(tmpdir) # delete the temp folder

相关问题 更多 >

    热门问题