0

我有很多文件,我想通过包含文件的创建日期来编辑所有名称。

这是我到目前为止所拥有的,但它不起作用:

a='c:\test_for_namn_andring\*.*';

file_info=dir('c:\test_for_namn_andring\*.*');

names={file_info.name};
dates={file_info.date};

for i=3:length(names)

   oldfilename = names;
   newfilename = (strcat(names(1,3:end), dates(1,3:end)));
   newfilename = fullfile(a, newfilename);
   movefile(fullfile(a,oldfilename{i}),newfilename);

end
4

2 回答 2

1

像这样的东西应该工作:

file_info = dir(a);

for ii = 1:length( file_info )
    if ~ file_info(ii).isdir
        oldName = fullfile( a, file_info(ii).name );
        newName = fullfile( a, sprintf( '%s_%s', file_info(ii).name, file_info(ii).date ) );
        movefile( oldName, newName );
    end
end

您可能还应该检查返回movefile以处理错误。有关更多信息,请参阅文档

于 2012-08-14T11:57:04.577 回答
1

我过去做过类似的事情。这是代码,已根据您的需要进行调整

% define params
folder = 'd:/test';
name_filter = '*.*';                % any filter, e.g. '*.txt'
date_format = '_yyyymmddHHMMSSFFF'; % define the desired date string format

% process
f = dir(fullfile(folder, name_filter));
f([f.isdir]) = [];
names = {f.name}';
fullnames_old = cellfun(@(x) fullfile(folder, x), names, 'UniformOutput', false);

dates = cellstr(datestr([f.datenum]', date_format));  
[pathstr, name, ext] = cellfun(@(x) fileparts(x), names, 'UniformOutput', false);
fullnames_new = cellfun(@(x, d, e) fullfile(folder, [x, d, e]), name, dates, ext, 'UniformOutput', false);
status = cellfun(@(x, y) movefile(x, y, 'f'), fullnames_old, fullnames_new);
assert(all(status), 'failed!');     % check result
于 2012-08-14T12:23:49.533 回答