Rename a file while copying

9 次查看(过去 30 天)
Anushi1998
Anushi1998 2017-6-15
评论: Y. K. 2018-1-17
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 个评论
Image Analyst
Image Analyst 2017-6-15
Are you trying to copy whole folders of files for multiple folders, instead of one file at a time for a single folder?
Anushi1998
Anushi1998 2017-6-15
I am copying files from multiple folders but each folder contain only one text file

请先登录,再进行评论。

回答(1 个)

JohnGalt
JohnGalt 2017-6-15
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 个评论
Y. K.
Y. K. 2018-1-17
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.
Y. K. 2018-1-17
I used this code to merge files in different folders to destination folder using source folder name as prefix of files.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by