Rename a file while copying
21 views (last 30 days)
Show older comments
I have a program in which I copy file from different location and paste it in a folder but some files have the same name so I want to change the name of that file to the folder of that from where I have copied.
I have almost developed the logic
Path='C:\Users\Anushi Maheshwari\Documents\Intern\shweta_traces\Benign';
cd (Path);
mkdir 'Traces';
rmdir('Traces','s');
folders=ls;
folders(1,:)=[];
folders(1,:)=[];
mkdir 'Traces';
for ii=1:length(folders)
str=folders(ii,:);
str=strcat(Path,'\',str);
cd (str);
traces=ls('*.txt*');
copyfile ('*.txt*',strcat((Path,'\Traces\',folders(ii,:),'\.txt'));
end
This code copies the file make a new folder in Traces folder and paste it there but what I want is to change the name of the file according to the subfolder and then paste it in Traces folder.
Any help is appreciated :-)
2 Comments
Image Analyst
on 15 Jun 2017
Are you trying to copy whole folders of files for multiple folders, instead of one file at a time for a single folder?
Answers (1)
JohnGalt
on 15 Jun 2017
hmm... ok so I'd recommend using 'dir' which returns a structure (see matlab help) ... also, look at the function 'fullfile' which takes foldernames as strings and handles all the path separators... I've broken up the strings into different lines for clarity...
try this:
Path='C:\Users\Anushi Maheshwari\Documents\Intern\shweta_traces\Benign';
cd (Path);
a = dir();
a(1:2) = []; % remove '.' and '..'
folderNames = a([a.isdir]==1).name;
destFolderName = 'Traces';
mkdir(destFolderName);
for ii=1:length(folders)
b = dir(fullfile(folderNames{ii},'*.txt'));
textFileName = b.name;
newTextFileName = [folderNames{ii} '_' textFileName] ;
fromString = fullfile(folderNames{ii},newTextFileName);
copyfile (fromString,'Traces');
end
2 Comments
Y. K.
on 17 Jan 2018
The code is tried and run as follows.
clear;clc;
Path='path name';
cd (Path);
a = dir();
a(1:2) = []; % remove '.' and '..'
folderNames = a([a.isdir]);
destFolderName = 'new folder name';
mkdir(destFolderName);
for ii=1:length(folderNames)
b = dir(fullfile(folderNames(ii).name,'*.bmp'));
for j=1:length(b)
textFileName = b(j).name;
newTextFileName = [folderNames(ii).name '_' textFileName] ;
fromString = fullfile(folderNames(ii).name,textFileName);
copyfile (fromString,newTextFileName);
movefile(newTextFileName,destFolderName);
end
end
Y. K.
on 17 Jan 2018
I used this code to merge files in different folders to destination folder using source folder name as prefix of files.
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!