Making a directory and adding it to the path
15 次查看(过去 30 天)
显示 更早的评论
Hello Community,
I am trying to create a new folder, named by user input and immediately have that folder added to the path. Currently, I am achieving this by two separate lines of code:
mkdir(input('Enter new folder name: ', 's'))
addpath(input('Enter Filename to be added to the path: \n', 's'))
but this is clunky as I have to manually enter the same information twice. I have tried this:
mkdir(genpath(input('Enter new folder name: ', 's')))
(also tried with addpath replacing genpath) but this doesn't work and generates the error:
Warning: An empty directory name was given. No directory will be created.
This syntax may not be supported in future releases.
So any thoughts on how I can combine the two commands ie to create a new folder and immediately add it and subfolders to the filepath?
Regards,
10B.
0 个评论
采纳的回答
Guillaume
2015-9-28
This is indeed very clunky. You seem to be allergic to variables, they're useful for storing information from one line to the next :)
while true
newfolder = input('Enter new folder name: ', 's');
[status, message] = mkdir(newfolder);
if ~status
sprintf('Failed to create folder because %s\n', message);
else
break; %get out of while loop
end
end
addpath(fullfile(pwd, newfolder)); %current folder is returned by pwd. Combined with newfolder gives full path.
Also note that I've added some error handling code, which you should always have when handling user input and / or filesystem. The user may enter invalid name, the folder may not be created due to permission, etc. It's always better to detect this than continue on your merry way.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Search Path 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!