Add directory to search path

조회 수: 2 (최근 30일)
Erik de Boer
Erik de Boer 2011년 1월 31일
Hello,
Some of my scripts use data from outside the working directory. I specify the data file by entering the entire path.
This works fine, however I'm forced to switch a lot between workstations. Those workstations have different names for the hard drive, which means I have to manually change all path specifiers every time I change PC's.
Since my data is always in the folder that is one down on the directory tree (i.e. the data is in the same folder as the folders containing my scrips are), I hope there is a way to make my scripts station independent.
Thanks for any tips.

채택된 답변

Michelle Hirsch
Michelle Hirsch 2011년 1월 31일
A couple of techniques come to mind, of various complexity and robustness.
Easy, but fragile
Build a partial path specifier. You just start with the name of the directory where the file lives, e.g.
filename = 'Data\myfile.txt';
This has a robustness issue, though. If the user runs your script from anywhere other than where the script lives, this won't work. It's even more fragile in interactive applications, since any time the user changes directories it will break.
A little harder, but more robust
Figure out once where the data directory is, then use this location every time you need to access a file. Assuming your scripts are just run straight through, the following should work:
% Get the directory of this script
p = which(mfilename);
parentDirectory = fileparts(p);
% Build a complete path to data directory. filesep returns the
% appropriate file separator on your platform
dataDirectory = [parentDirectory filesep 'My Data Folder' filesep];
% Reference a specific file by appending the name after the directory name
dataFile = [dataDirectory 'MyDataFile.txt']
HTH, - scott
  댓글 수: 3
Michelle Hirsch
Michelle Hirsch 2011년 1월 31일
I didn't use fullfile because I didn't think of it.
Erik - you may find that fullfile makes your code a bit more readable than using [] to build up the strings for dataDirectory and dataFile.
Erik de Boer
Erik de Boer 2011년 2월 1일
Thanks, but I prefer to use as few functions as possible. Initial answer works very well.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jiro Doke
Jiro Doke 2011년 1월 31일
Take a look at fileparts. You can use it to traverse back on the directory tree:
prevDir = fileparts(pwd)
  댓글 수: 2
Michelle Hirsch
Michelle Hirsch 2011년 1월 31일
You are fast, Jiro! Snuck this in while I was crafting my detailed, elegant answer! :)
Erik de Boer
Erik de Boer 2011년 1월 31일
Thanks Scott and Jiro, fileparts is exactly what I needed.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by