issue when creating and saving file to specific folder
3 views (last 30 days)
Show older comments
Hello, everyone. I got a small issue when creating a folder and saving files to it.
-------------------------------------------------------------------
monthStr = num2str(month);
mkdir(fullfile(folder,'Data',monthStr));
dataFolder = fullfile(folder,'Data',monthStr);
dataFolder
cd dataFolder ;
-----------------------------------------------------------------
Here I create a folder /Data/monthStr, where monthStr is a variable, for instance, it can be 202106
it is created under /folder/Data and 'dataFolder' shows its path correctly.
However, when I "cd dataFolder", error message says "Cannot CD to .... (Name is nonexistent or not a directory)."
Secondly, I like to save some downloaded file to this folder
--------------------------------------------------------------------
fullURL=['https://polar.ncep.noaa.gov/waves/hindcasts/multi_1/' monthStr '/gribs/multi_1.glo_30m.hs.' monthStr '.grb2';];
filename=[dataFolder,'multi_1.glo_30m.hs.' monthStr '.grb2'];
[f,status]=urlwrite(fullURL,filename);
--------------------------------------------------------------------
However, the file is saved to the "Data" folder, not "Data/monthStr" folder
Any idea to correct the code?
Thank you!
0 Comments
Answers (2)
Rik
on 17 Jun 2021
You shouldn't use cd outside of debugging. In general using a full path is a much better idea with better performance.
The cause of the error is that you used the command syntax, which doesn't allow the use of variables. In this case you would have needed to use cd(dataFolder).
For the second issue you forgot to add the filesep, which fullfile would have done automatically for you.
5 Comments
Rik
on 17 Jun 2021
Because there is a difference between Windows and Linux/Mac which character separates folders and files. You can automate this like this:
['folder' filesep 'subfolder' filesep 'file']
which is equivalent to this
fullfile('folder','subfolder','file')
Chunru
on 17 Jun 2021
When dataFolder is a variable, change directory with the following statement:
cd(dataFolder) ;
3 Comments
Stephen23
on 17 Jun 2021
Edited: Stephen23
on 17 Jun 2021
Avoid using CD in code: it is slow (MATLAB rescans the new folder for all MATLAB files and potentially caches them), changes function scope (which makes debugging harder) and is completely unnecessary.
Using absolute/relative filenames is the recommended approach (much more efficient, less buggy).
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!