How do i renaming files based on their folder names?

조회 수: 1 (최근 30일)
ahmed obaid
ahmed obaid 2017년 4월 16일
편집: dpb 2017년 4월 16일
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에서 Convert Image Type에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by