按顺序重命名文件夹中的文件

时间:2014-12-07 18:02:13

标签: matlab recursion logic rename

我在文件夹中有一堆随机名称的文件,我正在尝试将它们按顺序重命名为Sample1_1,Sample1_2,Sample2_1,Sample2_2,Sample3_1,Sample3_2等等......

到目前为止我的代码:

%%reading files in the directory and renaming it

files = dir('*.NEF');

for i = 1:name1(files)
    for j = 1:2
        filename = files(i).name;
        I = imread(filename);
        imwrite(I,sprintf('Sample%d_%d.NEF',i,j));
        delete(filename);
    end
end

1 个答案:

答案 0 :(得分:0)

这里有一个简单的代码,可以生成您想要的名称。为简化起见,我创建了2个数组,每个数组都包含我们要放入文件名的数字。然后很容易循环遍历数组并获得正确的数字。您的应用程序很容易实现:

clear
clc

%// In my example I generate only 8 names
NumSamples = 4;

CheckSample = kron(1:NumSamples,ones(1,2));
OneOrTwo = repmat([1 2],1,NumSamples);

CheckSample和OneOrTwo是我所指的2个数组。您可以看到对应关系以创建具有适当数字的文件名。

CheckSample =

     1     1     2     2     3     3     4     4


OneOrTwo =

     1     2     1     2     1     2     1     2

%// For demonstration purposes, create a cell array containing the filenames.
NameCell = cell(1,NumSamples*2);

%/ Now loop through each image (in your case) to generate the file name.

for k = 1:2*NumSamples

        NameCell{k} = sprintf('Sample%d_%d',CheckSample(k),OneOrTwo(k));

end

NameCell

NameCell看起来像这样:

NameCell = 

  Columns 1 through 4

    'Sample1_1'    'Sample1_2'    'Sample2_1'    'Sample2_2'

  Columns 5 through 8

    'Sample3_1'    'Sample3_2'    'Sample4_1'    'Sample4_2'

从上面的代码中你可以做到这样的事情:

    files = dir('*.NEF');
    NumSamples = length(files)/2;

    CheckSample = kron(1:NumSamples,ones(1,2));
    OneOrTwo = repmat([1 2],1,NumSamples);

for k = 1:2*NumSamples

    filename = files(k).name;
    I = imread(filename);

    CurrentName = sprintf('Sample%d_%d',CheckSample(k),OneOrTwo(k));
    CurrentName = strcat(CurrentName,'.NEF'); %// Keep right file extension.

    imwrite(I,CurrentName);

end