Save each result in different folders

1 view (last 30 days)
Hi I have 259 text file in a folder,P(1).txt:P(529).txt, and wanna change all their names to just P and save each one of then in a folder by their numbers, I could do it for one of them but when I got the code to for loop I got this error: ??? Error using ==> fprintf Invalid file identifier. Use fopen to generate a valid file identifier.
Error in ==> Untitled at 10
fprintf(fid2,'%s\n', str2{:});
any help will?
clc
clear
for i=2:530
fid1 = fopen(['P(' num2str(i-1) ').txt'],'r');
str1 = textscan(fid1,'%s','Delimiter','\n');
fclose(fid1);
OO=i-1
str2 = [str1{1}];
fid2 = fopen('E:\matlab\all\New folder\New folder (5)\VV\OO\P.txt','w');
fprintf(fid2,'%s\n', str2{:});
fclose(fid2);
end

Accepted Answer

Guillaume
Guillaume on 20 Jul 2018
If OO is supposed to be the generated folder name, then:
fid2 = fopen(sprintf('E:\\matlab\\all\\New folder\\New folder (5)\\VV\\%d\\P.txt', OO),'w');
Matlab is not going to automatically guess that you want to replace the characters 'OO' by the value of the OO variable.
After that line, I would also add:
assert(fid2 > 0, 'Failed to create file');

More Answers (0)

Categories

Find more on Data Import and Export 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!