Change names of files in a folder
13 次查看(过去 30 天)
显示 更早的评论
Hi I am trying to change all the file names in a folder I have of .tif images. I want to use the number of tif images in the file to be apart of the new save name.
INDIV = 'folder_path'; %
filenames_INDIV = dir(fullfile(INDIV, '*.tif')); % <-- 126x1 struct
original_images_indv = numel(filenames_INDIV); % <-- 126
for g = 1 : filenames_INDIV
for h = 1 : original_images_indv
[~, f] = fileparts(filenames_INDIV(h).name);
% write the rename file
rf = strcat(f,'SAM%03d', h) ;
% rename the file
movefile(filenames_INDIV(h).name, rf);
end
end
But I end up getting
Undefined function 'colon' for input arguments of type 'struct' for the first for statement
2 个评论
Adam
2019-10-22
Well, yes, as your own comments tell you filenames_INDIV is a (126x1) struct so using it as
1:filenames_INDIV
clearly won't work. I guess you could use
1:numel( filenames_INDIV )
although it isn't obvious to me what the outer loop does anyway since g is never referenced.
采纳的回答
Guillaume
2019-10-22
编辑:Guillaume
2019-10-22
In some ways your code is very well written with variable names that are descriptive and the correct functions used. In some other ways, it looks like it's been written by somebody who's just throwing random code at the wall and see what works. Puzzling!
Case in point, the line that gives you the error. You're iterating from 1 to ... a structure!? Matlab rightly tells you that it doesn't know how to do that, sorry, the : operator has no meaning when a structure is passed as an index. it's not even clear what the whole line is meant to do. The h loop on the following line would do the desired job on its own.
Then we have the strcat(f,'SAM%03d', h) which is again nonsense. It appears to be a strcat operation and sprintf operation all in one. It certainly won't produce the result required. Plus the new file name doesn't have an extension anymore.
And finally, we have the movefile which now longer use the folder path so will fail anyway since it will attempt to rename files in the current folder instead of the INDIV folder.
I suspect the code should be:
INDIV = 'folder_path';
filenames_INDIV = dir(fullfile(INDIV, '*.tif'));
for filenum = 1 : numel(filenames_INDIV);
[~, basename] = fileparts(filenames_INDIV(filenum).name);
newname = sprintf('%s_SAM%03d.tif', basename, filenum);
movefile(fullfile(INDIV, filenames_INDIV(filenum).name), fullfile(INDIV, newname));
end
0 个评论
更多回答(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!