Incrementing File names access
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Naveen Bandi
le 20 Nov 2017
Commenté : Naveen Bandi
le 21 Nov 2017
Hi all, I am facing trouble with reading file names in Matlab. My file names are like 05170201.001, 05170201.002, 05170201.003, 05170201.004. For every iteration I need to read a new file followed by the previous one.Every time the new file name just changes in the last two digits. So, can anybody please explain me how to do this.These are text files and the file number is numerous and I am not able to figure out the logic. Can anybody suggest.
Also one more question. While I concatenate two string say '05' and '010301' I get '05010301'. Once I convert this to number using str2num I get 5010301. The first number 0 is missing and I don't want this to happen. Can anybody suggest.
Any Help is sincerely appreciated.
Regards,
Naveen BM
0 commentaires
Réponse acceptée
Image Analyst
le 20 Nov 2017
Here's some fairly robust code:
filepattern = fullfile(pwd, '*.0*')
folderInfo = dir(filepattern)
% Sort filenames in case OS doesn't return them in sorted order.
[baseFileNames, sortOrder] = sort({folderInfo.name});
% Sort folderInfo the same way so they stay synced.
folderInfo = folderInfo(sortOrder);
% User wants to "read a new file followed by the previous one"
% so process files in REVERSE order.
% (Could also sort "decending" and do for loop in the forward order).
for k = length(baseFileNames) : -1 : 1
fullFileName = fullfile(folderInfo(k).folder,baseFileNames{k});
% Get the extension
[folder, baseFileNameNoExt, ext] = fileparts(fullFileName);
dblBaseName = str2double(baseFileNameNoExt); % If needed for some reason.
dblExt = str2double(ext(2:end));
if isnan(dblExt)
% extension is not a number
fprintf(' Skipping %s.\n', fullFileName);
continue;
end
fprintf('Now processing %s.\n', fullFileName);
% Else the extension is a number so do something with the file.
end
When you convert the base file name to a number, the leading zero doesn't matter. The number 05010301 is the same as the number 5010301. If you want the zero there for some reason, like to print to the command window with fprintf() like I did, then you'll need to keep it as a string.
Plus de réponses (1)
KL
le 20 Nov 2017
If your text files are in the same folder, then use dir,
folderInfo = dir('yourFolderName/*.txt');
This will return the filenames and some more properties of the text files. If you want to store the filenames alone in a cell array,
fileNames = {folderInfo.name};
Now that your file names are in this cell array, you can loop through it to do whatever you want,
for fno = 1:numel(fileNames)
currentFileName = fileNames{1};
%your operations
end
Voir également
Catégories
En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!