Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Matlab code - Copying multiple text files from different locations to the specified destination folder (Windows environment)

Asked by Prakash on 16 Sep 2013
Latest activity Answered by Jan Simon on 8 Oct 2013

Hi, Could someone please help me out with the matlab code for copying text files from different folders (Paths specified in a input text file) to the specified destination folder and archive it in *zip format..

-----------------------------------------------------------

Please find below, my Matlab code, for the above operation. The code doesn’t work as expected. It pops an error when compiled. Could someone please review the code and let me know where I am going wrong. Please help me..! Thank you.

Important stack variables used:

dat_stk - counter for no. of files to be copied i.e., 1 to 7

dat_bnn_include_stk - contains the immediate folder for the files i.e., b01, b02, b03, b04, b07, b09, b11

dat_include_stk - contains the path for all the files to be copied as mentioned below

Files to be copied:

'D:/abc/xyz/pqr/lmn/r1/sample/b01/a1.txt'
'D:/abc/xyz/pqr/aaa/r1/b02/b2.txt'
'D:/abc/xyz/pqr/aaa/r1/b03/c3.txt'
'D:/abc/xyz/pqr/aaa/r1/b04/d4.txt'
'D:/abc/xyz/pqr/aaa/r1/b07/e5.txt'
'D:/abc/xyz/pqr/aaa/r1/b09/f6.txt'
'D:/abc/xyz/pqr/aaa/r1/b11/g7.txt'

All these file paths (as shown in the same format above) would be available in a stack variable called ‘dat_include_stk’)

All these files need to be retrieved and copied to the specified path ‘D:/testfinal/ copy_all_files_sub_folders’ and archive the folder as "copy_all_files_sub_folders.zip" using MATLAB routines

*Matlab code: *

clc    
copy_all_se_dir_switch=1;    
for i=1:length(dat_stk);    
    dum=char(dat_include_stk(i,:)); dum=['''' dum '''']
    for j = 1:(length(dum)-1);    
        if dum(j) == '\' ;  dir_stem_length=j;      % routine to work out dir stem lengths... PC    
        elseif dum(j) == '/' ;  dir_stem_length=j;  % routine to work out dir stem lengths... UNIX    
        end    
    end    
end    
stk=[];stk1=[];     
    if exist('asm_stk','var') == 0;
        errordlg(['Error!    Write Nastran deck first']);
        fclose('all');break
    else
    end
stk=[];
for i=1:length(dat_stk);
    dum=char(dat_include_stk(i,:));
    dum2=dum(dir_stem_length-4:dir_stem_length-2);
    stk=[stk;dum2];
end    
dat_bnn_include_stk=stk;    
copy_files_dir=uigetdir('','Select Directory to copy files to');  
fid=fopen('copy_all_files_sub_folders.run','w');     
fprintf(fid,'%s\n',['!cd' copy_files_dir]);    
fprintf(fid,' \n',[]);    
% bulks
fprintf(fid,' \n',[]);  
for i = 1:length(dat_stk);  
    fprintf(fid,'%s\n',['mkdir ' dat_bnn_include_stk(i,:)]);
    fprintf(fid,'%s\n',['copyfile ' char(dat_include_stk(i,:)) ' ' 
dat_bnn_include_stk(i,:) '/' ]);    
end    
fprintf(fid,' \n',[]);     
dum=get(h404,'string');    
if isempty(dum)==1    
    fprintf(fid,'%s\n',['copyfile ' file_op_dir '/' master_nas_fname ' .']);  
else     
    fprintf(fid,'%s\n',['copyfile ' long_filename ' .']);
end    
fprintf(fid,' \n',[]);
fprintf(fid,'%s\n',['cd ../']);    
clear fid;  
fclose('all');
copy_all_se_dir_switch=0;
if OS=='PCWI'    
    winopen ('copy_all_files_sub_folders.run')
else
   !nedit copy_all_files_sub_folders.run
   zip('copy_all_files_sub_folders.zip','copy_all_files_sub_folders');
end

Error Message:

??? Error using ==> win_open_mex
There is no application associated with the given file name extension.
Error in ==> winopen at 54
win_open_mex(pathstr, filename);
Error in ==> mytest_Bulkwrap at 94
winopen ('copy_all_files_sub_folders.run')

0 Comments

Prakash

Products

No products are associated with this question.

3 Answers

Answer by Prakash on 17 Sep 2013
Edited by Prakash on 17 Sep 2013

Please find below, my Matlab code, for the above operation. The code doesn’t work as expected. It pops an error when compiled. Could someone please review the code and let me know where I am going wrong. Please help me..! Thank you..!!!

Important Variables used:

dat_stk - counter for no. of files to be copied i.e., 1 to 7

dat_bnn_include_stk - contains the immediate folder for the files i.e., b01, b02, b03, b04, b07, b09, b11

dat_include_stk - contains the path for all the files to be copied

Files:

'D:/abc/xyz/pqr/lmn/r1/sample/b01/a1.dat'

'D:/abc/xyz/pqr/aaa/r1/b02/b2.dat'

'D:/abc/xyz/pqr/aaa/r1/b03/c3.dat'

'D:/abc/xyz/pqr/aaa/r1/b04/d4.dat'

'D:/abc/xyz/pqr/aaa/r1/b07/e5.dat'

'D:/abc/xyz/pqr/aaa/r1/b09/f6.dat'

'D:/abc/xyz/pqr/aaa/r1/b11/g7.dat'

All these files need to be copied to the path D:/testfinal/ copy_all_files_sub_folders and archive the folder as "copy_all_files_sub_folders.zip"

Matlab Code:

clc

copy_all_se_dir_switch=1;

for i=1:length(dat_stk);

        dum=char(dat_include_stk(i,:)); dum=['''' dum ''''];
        for j = 1:(length(dum)-1);
        if dum(j) == '\' ;  dir_stem_length=j;      % routine to work out dir stem lengths... PC
        elseif dum(j) == '/' ;  dir_stem_length=j;  % routine to work out dir stem lengths... UNIX
        end
        end

end

stk=[];stk1=[];

            if exist('asm_stk','var') == 0;
            errordlg(['Error!    Write Nastran deck first']);
            fclose('all');break
            else end

stk=[];

% stripping off the files to be copied *.txt

for i=1:length(dat_stk);

    dum=char(dat_include_stk(i,:));
    dum2=dum(dir_stem_length-4:dir_stem_length-2);
    stk=[stk;dum2];

end

dat_bnn_include_stk=stk;

copy_files_dir=uigetdir('','Select Directory to copy files to');

fid=fopen('copy_all_files_sub_folders.run','w');

fprintf(fid,'%s\n',['!cd' copy_files_dir]);

fprintf(fid,' \n',[]);

fprintf(fid,' \n',[]);

for i = 1:length(dat_stk);

 fprintf(fid,'%s\n',['mkdir ' dat_bnn_include_stk(i,:)]);
 fprintf(fid,'%s\n',['copyfile ' char(dat_include_stk(i,:)) ' ' dat_bnn_include_stk(i,:) '/' ]);

end

fprintf(fid,' \n',[]);

dum=get(h404,'string');

if isempty(dum)==1

fprintf(fid,'%s\n',['copyfile ' file_op_dir '/' master_nas_fname ' .']);

else

fprintf(fid,'%s\n',['copyfile ' long_filename ' .']);

end

fprintf(fid,' \n',[]);

fprintf(fid,'%s\n',['cd ../']);

clear fid;

 fclose('all');
 copy_all_se_dir_switch=0;

if OS=='PCWI'

winopen ('copy_all_files_sub_folders.run')

else

!nedit copy_all_files_sub_folders.run

zip('copy_all_files_sub_folders.zip','copy_all_files_sub_folders');

end

---------------- Thank you..!!!

5 Comments

Jan Simon on 17 Sep 2013

@Prakash: You can see it also, that the code still looks ugly. While inserting a blank line after each line of code just looks bad, a proper formatting is such easy: Use Ctrl-I for a smart indentation in Matlab's editor, post the code in the forum, leave one blank line before and after the code, mark the code with the mouse and press the "{} Code" button.

When you explain "It pops an error when compiled", posting the error message would be a good idea. I cannot imagine, why you compile the code. Creating a batch file dynamically and open it by winopen is very strange. Why not using Matlab for this directly? The indirection increases the complexity of the code dramatically. Better use the Matlab command MKDIR and COPYFILE.

Prakash on 18 Sep 2013

@Jan Simon: I have formatted the code in the original post as suggested. Also , I've posted the error message in the post. Please find below, the same message, for ur ref.. Error Message:

??? Error using ==> win_open_mex

There is no application associated with the given file name extension.

Error in ==> winopen at 54

win_open_mex(pathstr, filename);

Error in ==> mytest_Bulkwrap at 94

winopen ('copy_all_files_sub_folders.run')

Could you please let me know the changes that need to be done to the code..

Thanks!

Jan Simon on 18 Sep 2013

Yes, you have posted an error message, but this message does not appear "when compiled". As far as I can see, you do not "compile" anything. So this detail is confusing only.

Look in my next answer for a properly formatted code and compare it with your version. Do you see the difference?

Prakash
Answer by Jan Simon on 18 Sep 2013
Edited by Jan Simon on 18 Sep 2013

After some discussions here a properly indented and formatted version of the code:

clc
copy_all_se_dir_switch=1;
for i=1:length(dat_stk);
  dum = char(dat_include_stk(i,:));
  dum = ['''' dum ''''];
  for j = 1:(length(dum)-1);
    if dum(j) == '\'
       dir_stem_length=j;      % routine to work out dir stem lengths... PC
    elseif dum(j) == '/'
       dir_stem_length=j;      % routine to work out dir stem lengths... UNIX
    end
  end
end
stk=[];
stk1=[];
if exist('asm_stk','var') == 0;
  errordlg(['Error!    Write Nastran deck first']);
  fclose('all');
  break
end
stk=[];
% stripping off the files to be copied *.txt
for i=1:length(dat_stk);
  dum=char(dat_include_stk(i,:));
   dum2=dum(dir_stem_length-4:dir_stem_length-2);
  stk=[stk;dum2];
end
dat_bnn_include_stk=stk;
copy_files_dir=uigetdir('','Select Directory to copy files to');
fid=fopen('copy_all_files_sub_folders.run','w');
fprintf(fid,'%s\n',['!cd' copy_files_dir]);
fprintf(fid,' \n',[]);
fprintf(fid,' \n',[]);
for i = 1:length(dat_stk);
  fprintf(fid,'%s\n',['mkdir ' dat_bnn_include_stk(i,:)]);
  fprintf(fid,'%s\n',['copyfile ' char(dat_include_stk(i,:)) ' ' ...
          dat_bnn_include_stk(i,:) '/' ]);
end
fprintf(fid,' \n',[]);
dum=get(h404,'string');
if isempty(dum)==1
  fprintf(fid,'%s\n',['copyfile ' file_op_dir '/' master_nas_fname ' .']);
else
  fprintf(fid,'%s\n',['copyfile ' long_filename ' .']);
end
fprintf(fid,' \n',[]);
fprintf(fid,'%s\n',['cd ../']);
clear fid;
fclose('all');
copy_all_se_dir_switch=0;
if OS=='PCWI'
  winopen ('copy_all_files_sub_folders.run')
else
  !nedit copy_all_files_sub_folders.run
  zip('copy_all_files_sub_folders.zip','copy_all_files_sub_folders');
end

I recommend to remove the complete code, because it is too indirect and complicated, wuch that trying to repair it will be confusing only.

Do not call the operating system for COPYFILE, CD, MKDIR etc, but perform the jobs inside Matlab - the required commands have the same names.

In the first loop "for i=1:length(dat_stk)", the variable "dir_stem_length" is overwritten repeatedly. Therefore I cannot guess the intention of the code and in consequence not suggest an improvement.

The "break" is most likely misplaced - I do not see the concerned loop here.

What is "OS"? Comparing strings by == fails, if the strings have different lengths. So better use STRCMP.

I cannot recognize the relation between the code and your description in the original message. Does "Conditions: With the click of a drop down list in GUI, please read in 'INPUT' text file" play any role?

I find two not matching information:

 1. Files to be copied:
 D:/test1/a1.txt
 D:/test2/b2.txt
 ...
 2. Files to be copied:
 'D:/abc/xyz/pqr/lmn/r1/sample/b01/a1.txt'
 'D:/abc/xyz/pqr/aaa/r1/b02/b2.dat'
 ...

Therefore I'm still not sure how the list of files to be copied is defined. I guess you need a few lines of code only, perhaps something like this:

Data = fileread('TheInputFile.txt');
FileC = regexp(Data, '\n', 'split');
DestFolder = 'D:/testfinal';
mkdir(DestFolder);
NameC = cell(1, length(FileC));
for iFile = 1:length(FileC)
  copyfile(FileC{iFile}, DestFolder);
  [dummy, name, ext] = fileparts(FielC{iFile});
  NameC{iFile} = [name, ext];   % [EDITED] iC -> iFile
end
zip('copy_all_files_sub_folders.zip', NameC, DestFolder);

12 Comments

Jan Simon on 7 Oct 2013

@Prakash: No, there is no problem of copyfile. The file names are still wrong. It would reduce the time of this discussion, if you provide the input data in valid Matlab syntax. Why do you refuse to post the contents of dat_include_stk in valid Matlab syntax? It would take some seconds only to suggest the required changes afterwards.

Valid names of existing files contain double quotes only, if the names of the files contain double quotes. But this is usually not the case, so where do the double quotes come from? Why do you assume that they belong to the file names, although the error message created by copyfile explains explicitly, that such a file does not exist?

And let me repeat it again: The names you are providing are not existing files. This is not a problem of copyfile, but one of the file names. The only way to copy a file successfully is to use the correct file name. With a wrong file name, there is absolutely no chance to access the file. And as the error message tells you clearly, the names are wrong.

We are discussing for 2 weeks now, but the problem is really trivial.

Prakash on 8 Oct 2013

@Jan Simon, thanks again. Please find the contents of dat_include_stk below;

      dat_include_stk = 
      "D:/source/testfiles/r1/b01/test1.txt"
      "D:/source/testfiles/r1/b02/test2.txt"
      “D:/source/testfiles/r1/b03/test3.txt”
      “D:/source/testfiles/r1/b04/test4.txt”
      “D:/source/testfiles/r1/b07/test5.txt”
      “D:/source/testfiles/r1/b09/test6.txt”
      “D:/source/testfiles/r1/b11/test7.txt”
The above files (contents may be arbitrary) should be copied to the destination folder (Matlab root directory) given below -
   C:/Users/User1/Documents/MATLAB/testfinal/

The above code is tested for this case but it still provides the same error message (with status of '0' and the message is 'No matching files were found.'). Could you please suggest some ways to overcome this error. Thanks..

Jan Simon on 8 Oct 2013

@Prakash: Wow. This thread frustrates me. I've repeated it several times, that it would be helpful, if you post the definition of data_include_stk in valid Matlab syntax. Now you post it again in a format, which is not well defined and especially still not Matlab syntax. Try it by your own: Select this with the mouse, copy it, paste it to the command windows and try to run it:

dat_include_stk = 
    "D:/source/testfiles/r1/b01/test1.txt"
    "D:/source/testfiles/r1/b02/test2.txt"
    “D:/source/testfiles/r1/b03/test3.txt”

It is not my job to guess, what you mean. But if it would be my job, I'd suggest:

dat_include_stk = { ...
    '"D:/source/testfiles/r1/b01/test1.txt"', ...
    '"D:/source/testfiles/r1/b02/test2.txt"', ...
    '“D:/source/testfiles/r1/b03/test3.txt”'}

Now try to copy and paste this. Do you see the difference? While the above version you have posted produces an error message, my version creates a cell string.

I've told you already, that the double quotes are wrong here and do not belong to the file name. You again post the file names with double quotes. But why? You even use the typographic double quotes “ and ”, not the standard version ". I cannot guess if this is caused by formatting the text in MS Word at first or if these different double quotes do really exist in the definition of your file names. But in any way: The double quotes must be removed.

I'm going to create one last answer and afterwards I will not care about this thread anymore. The suggestion to cleanup the file names have been ignored by you demonstratively. If my suggestion contains any further problem, I'm convinced, that they cannot be solved. Then I'd suggest to you to give up working with Matlab.

Good luck.

Jan Simon
Answer by Jan Simon on 8 Oct 2013
Data       = fileread('TheInputFile.txt');
FileC      = regexp(Data, '\n', 'split');
DestFolder = 'C:/Users/User1/Documents/MATLAB/testfinal/';
mkdir(DestFolder);
% Or perhaps:
% FileC = dat_include_stk;
% Now clean up the file names:
FileC = strrep(FileC, '"', '');
FileC = strrep(FileC, '“', '');   % If such junk is really existing
FileC = strrep(FileC, '”', '');   % If such junk is really existing
FileC = FileC(~cellfun('isempty', FileC));  % remove empty names
NameC = cell(1, length(FileC));
for iFile = 1:length(FileC)
  aFile = FileC{iFile};
  if exist(aFile, 'file') ~= 0
    [status, message] = copyfile(aFile, DestFolder);
    if status ~= 1
      error(message);
    end
    [dummy, name, ext] = fileparts(aFile);
    NameC{iFile} = [name, ext];
  else
    fprintf(2, 'There is no file with this name: %s\n', aFile);
  end
end
zip('copy_all_files_sub_folders.zip', NameC, DestFolder);

If you still get errors with this, I give up. Then try to fix them by your own, because it is obviously beyond my possibilities to help you.

0 Comments

Jan Simon

Contact us