How to extract only one file from a zipped folder
25 次查看(过去 30 天)
显示 更早的评论
I have a zipped folder with multiple subfolders in it. The subfolders aren't zipped but I want to extract two files from a subfolder of a subfolder. I have about 1000 subjects that I want to do this for so I have to make a for loop and cannot do it by individual commands.
path_r = 'H:/emotion/data/';
cd(path_r)
subj_list = dir('*');
subj_list(1:2) = [];
for subji = 1%:length(subj_list)
path = [path_r subj_list(subji).name '/MNINonLinear/Results/tfMRI_EMOTION_RL/'];
^ this is the code for to the folder with the file
unzip([path 'tfMRI_EMOTION_RL.nii.gz'], ['H:/emotion/' subj_list(subji).name '_RL'])
unzip([path 'Motion_Regressors'], ['H:/emotion/' subj_list(subji).name '_RL'])
^These are the two files I want to extract to a new folder
end
The subject list is the name of the subject ex. 123456. However, the only way to get this list is if I extract the files. The true name of the file is "123456_3T_rfMRI_REST1_preproc" so I would need to find a way to make a subject list with only the numerical subject name because it is required for the path. Please let me know what I can do to change my code and make sure it works.
0 个评论
回答(2 个)
chrisw23
2023-4-18
NET.addAssembly("System.IO.Compression.FileSystem");
NET.addAssembly("System.IO.Compression");
function [unzippedFileNames,msg] = unzipFromArchive(obj,zipArchivePath,searchString,ignoreCase,unzipPath)
% unzip specific files from given archive
% search string can bei a complete file name or a related part of the file name
% '*' wildcards are not supported
import System.IO.*
import System.IO.Compression.*
import System.IO.Compression.ZipFileExtensions.*
msg = obj.DefaultNoError;
archStream = File.Open(zipArchivePath, FileMode.Open);
try
arch = ZipArchive (archStream, System.IO.Compression.ZipArchiveMode.Read);
zipFileList = NET.createGeneric('System.Collections.Generic.List',{'System.String'},arch.Entries.Count);
enArch = arch.Entries.GetEnumerator;
overwrite = true;
while enArch.MoveNext
zipFileList.Add(enArch.Current.Name);
end
zipFiles = string(zipFileList.ToArray)';
searchIndex = find(zipFiles.contains(searchString,'IgnoreCase',ignoreCase)); % zero based .net index
unzippedFileNames = zipFiles(searchIndex); % search result
if ~isempty(searchIndex)
for sglFileIndex = searchIndex'
ZipFileExtensions.ExtractToFile (arch.Entries.Item(sglFileIndex-1),Path.Combine(unzipPath,zipFiles(sglFileIndex)), overwrite)
end
else
msg = "archive file names without match to search string '" + searchString + "'";
end
catch ex
msg = ex.message;
unzippedFileNames = [];
end
% release archive file
arch.Dispose();
archStream.Close();
end
modify this as needed (copied out of one of my classes)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!