MATLAB编程技巧:批量查找文件并复制至目标文件夹
平常我们在Windows电脑中查找某个文件夹下有多种类型的文件,一个一个的查找出来比较麻烦,因此,利用MATLAB编写一个小脚本,即可实现对特定类型文件的查找,并复制至目标的文件夹下,主要是利用MATLAB中的copyfile函数实现对文件的复制。
脚本如下所示:
function Code_copyfile(filePath,fileType,destinationPath)
fig = find_files_in_dir(filePath,fileType);
for i = 1:length(fig)
figpath = fig{i,1};
figname = fig{i,2};
FilePath = [figpath,filesep,figname];
copyfile(FilePath,destinationPath);
end
function total_list = find_files_in_dir( start_dir, filetype )
subdirectories = genpath( start_dir );
if ispc
subdirectories = regexp( subdirectories, '[^;]*', 'match' );
else
subdirectories = regexp( subdirectories, '[^:]*', 'match' );
end
filetype = strrep( filetype, '.', '' );
total_list = { };
for i = 1:length( subdirectories )
files = dir( subdirectories{ i } );
files = files( ~[ files.isdir ] );
files = { files.name }';
if ~strcmpi( filetype, '*' )
for j = 1:length( files )
if strcmpi( file_get_extension( files{ j } ), filetype )
total_list{ end + 1, 1 } = subdirectories{ i };
total_list{ end , 2 } = files{ j };
end
end
else
if ~isempty( files )
directories = cell( length( files ), 1 );
[ directories{ 1:end } ] = deal( subdirectories{ i } );
total_list = [ total_list;[ directories, files ] ];
end
end
end
function extension = file_get_extension( filename )
extension = '';
idx = findstr( filename, '.' );
if ~isempty( idx )
extension = filename( idx + 1:end );
end
以下是函数应用的示例:
Code_copyfile('E:\','.jpg','C:\Users\zengf\Desktop\图片')
函数的输入参数含义:
filePath:文件夹路径
fileType:文件类型
destinationPath:复制文件的文件夹路径