Effacer les filtres
Effacer les filtres

How to continue for loop if file not found?

4 vues (au cours des 30 derniers jours)
jschen1
jschen1 le 31 Oct 2020
Commenté : jschen1 le 1 Nov 2020
Hi all,
I'm trying to sort through subfolders on a remote server (i.e there is a folder for each year, and within each year is 12 months, each in their own folder, and then each monthly folder has a file for each day and I am looking at those daily files). So I created some code to sort through each file, but the issue is that there is no files for two of the months. How can I tell the code to skip those years? Here is my code:
path = '/' %just the path to the directory
finaldata = NaN(37,365);
for year = 1979:2015
for month = 1:12
string_year = string(iyear);
string_month = sprintf('%02d',imonth);
filepath = path + string_year + '/' + string_month + '/';
folders = dir(file_path +'*.nc');
filename = folders.name;
files = filepath + filename;
if ~isfile(files)
continue;
end
for day = 1:length(files)
%some code on data processing
%x is output of data, which is a single number for each file and then that is put in the empty array
finaldata(month,day) = x;
end
end
end
Here is the section in question:
if ~isfile(files)
continue;
end
I keep getting an error that says "Insufficent number of outputs from the right hand sign of equal sign to satisfy argument" in reference to the line "filename = folders.name", so I don't think it is working. Thank you!
  1 commentaire
jschen1
jschen1 le 31 Oct 2020
I also am worried I have it in the wrong location, so any insight on that would really help!

Connectez-vous pour commenter.

Réponse acceptée

Adam Danz
Adam Danz le 31 Oct 2020
Modifié(e) : Adam Danz le 31 Oct 2020
First, "file_path" should be filepath to match the pre-defined variable name 3 lines above.
Second, if the filepath does not exist, folders will be empty,
folders = dir(filepath +'*.nc');
so a better test would be,
folders = dir(file_path +'*.nc');
if ~isempty(folders) % <---test
filename = folders.name;
files = filepath + filename;
for day = 1:numel(files) % <--- use numel instead of length
% [ STUFF ]
end
end
Make sure you're preallocating any loop variables in case iterations are skipped!
  1 commentaire
jschen1
jschen1 le 1 Nov 2020
Thank you so much Adam, this worked perfect!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by