How do i renaming files based on their folder names?

5 次查看(过去 30 天)
Dear all
i have many folders that exist in certain directory.. every folder includes some images with ambiguous name.. i would like to rename these images based on their its parent folder name.. but the problem in the following code .. images names are numbers like (1245451116 , 4654646654, 44465464 ....) and this code do not able to renaming its :
result perhaps look like the following : folder1 images names becomes : folder1-1; folder1-2; .... folder2 images names becomes: folder2-1; folder2-2; etc...
projectdir = 'D:\RESULT\Evaluation\categorized';
dinfo = dir(projectdir);
dinfo(~[dinfo.isdir]) = []; %remove non-folders
dinfo(ismember({dinfo.name}, {'.', '..'})) = []; %remove . and .. directories
num_subdir = length(dinfo);
for S = 1 : num_subdir
this_subdir = dinfo(S).name;
subdinfo = dir( fullfile(projectdir, this_subdir, '*.jpg') );
num_subfile = length(subdinfo);
for F = 1 : num_subfile
this_file = subdinfo(F).name;
old_file = fullfile( projectdir, this_subdir, this_file );
new_file = fullfile( projectdir, this_subdir, [this_subdir '-' this_file] );
try
movefile(old_file, new_file);
catch ME
fprintf('Failed to rename "%s" to "%s"\n', old_file, new_file );
end
end
end

回答(1 个)

dpb
dpb 2017-4-16
编辑:dpb 2017-4-16
...
for F=1:length(subdinfo) % no need for temporary variable here
[~,n,e]=fileparts(subdinfo(F).name); % get the name, extension
fname=sprintf('%s-%04d%s%s',this_subdir,n,F,e); % build new name from the pieces-parts
try
movefile(fullfile(projectdir,this_subdir,this_file),fullfile(projectdir,fname);
...

类别

Help CenterFile Exchange 中查找有关 Biological and Health Sciences 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by