issue when creating and saving file to specific folder
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Rik
2021-6-17
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 个评论
Rik
2021-6-17
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
2021-6-17
When dataFolder is a variable, change directory with the following statement:
cd(dataFolder) ;
3 个评论
Stephen23
2021-6-17
编辑:Stephen23
2021-6-17
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).
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!