MATLAB: How to copy and rename files in a different folder

copyfile; movefileMATLAB

Hi all,
Let's say I have 3 text files (001X, 002Y and 003Z) in the folder A. Now, I want to first move these files to a created folder B and then rename them like so: 001_T, 002_T and 003_T) so I now have the old files in folder A and the new renamed ones in folder B. I'm almost done but my code (below) doesn't quite work. Any ideas? Thank you.
%First create the folder B
CurrentDirectory=pwd;
if exist([pwd '\B'])~=7
mkdir B
end
%Move the files with copyfiles ?
%Then rename the files
A =dir( fullfile('*.txt') );
fileNames = { A.name };
for iFile = 1 : numel( A )
movefile(A(iFile).name,[A(iFile).name(1:3) '_T.txt']);
end

Best Answer

Try this:
% First create the folder B, if necessary.
outputFolder = fullfile(pwd, 'B')
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
% Copy the files over with a new name.
inputFiles = dir( fullfile('*.txt') );
fileNames = { inputFiles.name };
for k = 1 : length(inputFiles )
thisFileName = fileNames{k};
% Prepare the input filename.
inputFullFileName = fullfile(pwd, thisFileName)
% Prepare the output filename.
outputBaseFileName = sprintf('%s_T.txt', thisFileName(1:end-4));
outputFullFileName = fullfile(outputFolder, outputBaseFileName)
% Do the copying and renaming all at once.
copyfile(inputFullFileName, outputFullFileName);
end