Rename a file while copying

15 ビュー (過去 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 Center および File ExchangeFile Operations についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by