访问.zip存档中的文件而不提取它们

时间:2018-01-26 05:58:09

标签: python zip zipfile nifti

我试图在.zip中读取NIFTI文件,而不必将目录解压缩到根目录。更具体地说,我正在使用ADNI数据库,文件由subjectID存储在单独的.zip文件中。在.zip文件中有关于该主题的所有数据,我想从.zip中提取NIFTI文件(.nii.gz)而不提取文件。

目前我有以下代码段

def openNIFTI(filename):
   return nib.load(filename).get_data()

zip_filename = filepath + str(subject_id) + '_3T_Structural_unproc.zip'
filename = str(subject_id) + '/unprocessed/3T/T1w_MPR1/' + str(subject_id) + '_3T_T1w_MPR1.nii.gz'

file = zf.extract(filename)
data = openNIFTI(file)

filepath 是.zip文件集合的路径。 filename 是.zip文件中我想要提取的NIFTI文件的路径。

(编辑)

似乎错误来自nibabel加载功能。然后进行功能检查

if not op.exists(filename):

独立测试os.path.exists(filename)函数后,我发现了。

os.path.exists(r'C:/Users/eee/workspace_python/Image Reconstruction/data/ADNI/MRI data/100206_3T_Structural_unproc.zip/100206/unprocessed/3T/T1w_MPR1/100206_3T_T1w_MPR1.nii.gz')
  

但是,此路径是从我尝试打开的文件中复制/粘贴的。在我看来,由于文件路径中的.zip而出现错误,因为

os.path.exists(r'C:/Users/eee/workspace_python/Image Reconstruction/data/ADNI/MRI data/100206_3T_Structural_unproc.zip')
  

还有另一种方法吗?

1 个答案:

答案 0 :(得分:1)

请参阅python: Open file from zip without temporary extracting it的已接受答案,其中显示了如何在不提取文件的情况下从zipfile中读取数据(当然,您需要足够的RAM来处理文件内容)。

相关问题