How do I check if a folder exists which has a variable name?
조회 수: 12 (최근 30일)
이전 댓글 표시
Hi,
I want to check if the created folder already exists. But the name of the folder depends on the file I work with.
fname = Measurement_20190829_18_15_10.bin
if ~exist('Figures' fname(11:end-4), 'dir')
mkdir('Figures', fname(11:end-4));
end
I have no clue how to make this work.
I always get Invalid expression with a marker on fname.
Please help.
Thank you!
댓글 수: 3
Stephen23
2019년 8월 29일
편집: Stephen23
2019년 8월 29일
"How does fileparts help me in this example?"'
Instead of using this fragile, very non-robust code to obtain the filename without the extension:
fname(11:end-4)
you can simply use robust fileparts:
[~,name] = fileparts(fname);
"But the exist does not work properly."
exist does work properly. Read the last four lines of my previous comment.
채택된 답변
Stephen23
2019년 8월 29일
편집: Stephen23
2019년 8월 29일
[~,name] = fileparts(fname);
exist(fullfile('Figures',name), 'dir')~=7
Note that exist does NOT return a boolean value, it returns different integers for specific object types. It is strongly recommended to test for the specific integer that is returned for the specific object type that you are trying to locate.
추가 답변 (1개)
Johannes Fischer
2019년 8월 29일
편집: Johannes Fischer
2019년 8월 29일
Your code is trying to store in fname the content of the field 'bin' of the struct 'Measurement_20190829_18_15_10', which propably doesnt exist.
fname needs to be a char array:
fname = 'Measurement_20190829_18_15_10.bin';
I have no idea about your folder structure, but Im guessing its 'Figures\t_20190829_18_15_10' ? If so, you would need to write
mkdir(['Figures\', fname(11:end-4)]);
and the same as the argument for 'exist'
댓글 수: 5
Stephen23
2019년 8월 29일
"..but how should it look like with my code."
See my answer.
It uses more robust fileparts rather than fragile indexing.
It uses simple fullfile to join the folder and file names.
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!