Matlab code - Copying multiple text files from different locations to the specified destination folder (Windows environment)
Show older comments
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')
Answers (3)
5 Comments
@Prakash: Please do not misuse flags to catch attraction to your question. They are thought to call the admins when a message conflicts with the terms of use of the forum.
Please post the relevant part of the code in the original question and not in a pseudo-answer.
Please format your code properly when you want others to read it. Code formatting is discussed such frequently, that you will surely find the required instructions by your own.
Please post a copy of the complete error message, when you get one. It is much easier to solve a problem than to guess, where and what it is.
These 4 suggestions for improvements mean, that you can and should increase the quality of the question to allow for an efficient creation of an answer.
Prakash
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
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?
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
on 18 Sep 2013
Dear Prakash: Of course my code will not run, because I guessed some details. It is thought as a pattern only to demonstrate how to avoid the too complicated construction of commands evaluated by the operating system.
What does "the Matlab stack variable 'dat_include_stk[ ]'" mean? Names of variables cannot contain square brackets, a stack type of variables does not exist, but the data look like you mean a cell string (then the square brackets are confusing).
If you have the file names in a cell string already, you can omit the first two lines of my code and replace "NameC" by your "dat_include_stk".
I've shown enough methods to solve the problem. Now it is your turn to elaborate this.
Prakash
on 19 Sep 2013
Jan
on 19 Sep 2013
@Prakash: The error message means, that the name in "FileC{iFile}" is not an existing file. You do not have to change NameC, because this is an output of the code, but FileC, which is the input. I suggest to catch problems:
[status, message] = copyfile(FileC{iFile},DestFolder);
if status ~= 1
error(message);
end
Prakash
on 20 Sep 2013
@prakash: Of course the error does not disappear, when a proper error message is created. But the error message should help you to understand the problem.
sprintf is not meaningful here. Please do not start to guess around. dat_include_stk{iFile} should be a string already and if you are not sure about this, check it by using the debugger and:
ischar(dat_include_stk{iFile})
Do you have any evidence that sprintf is useful here? The error message tells you: "No matching files were found.".
I've suggested a code to catch errors of copyfile. It is really recommended to catch the status of file operations in every case. But the code you have posted omits this test again. Why?
The shown code fails, if a string stored in the cell string dat_include_stk is not an existing file. This is not a problem of converting strings, but the file name is wrong. Perhaps the path is missing?
Prakash
on 24 Sep 2013
Jan
on 24 Sep 2013
@Prakash: Please use valid Matlab syntax when you post data. This is not a valid syntax:
dat_include_stk =
''D:/abc/xyz/pqr/lmn/r1/sample/b01/a1.txt''
Try to insert it in the command window by copy&paste. You cannot include a string in two single quotes in Matlab. Therefore I cannot guess, what this is exactly. In the text you talk of "double quotes", but this is totally different from two single quotes.
You have two copyfile commands in the code. Better use one only to reduce the confusion.
If the leading space and the single or double quotes prevent a successful copy, remove the leading space and the single or double quotes. The STRREP command looks fine for this job.
Do you see that this thread is rather inefficient? I cannot guess, why your strings are no existing file names, and it is hard to guess the reasons for this. Please use the debugger to find out more details by your own.
Prakash
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
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
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.
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!