reading the file from different directories

26 次查看(过去 30 天)
How to read a file_2 of different directory from the file_1 of the working directory without adding the full path of file_2 in file_1?
  5 个评论
Dyuman Joshi
Dyuman Joshi 2024-3-26
You would have to provide the path to the file(s).
Or (if possible and more conveniant,) directly provide the file.
(These are the only possibilites I could come up with now, I'll update if some other ideas come up)
If the folder structure is not available, then, would using dir to get the folder structure work or not?
Stephen23
Stephen23 2024-3-26
"What if I share my local repo to some other matlab user, where my folder structure is not available? "
Let them specify the location of their own data files.

请先登录,再进行评论。

回答(1 个)

prabhat kumar sharma
Hi Rajesh,
I Understand you are looking for a method to use a file that is not in the current directory within another file.
Here are several effective methods you might consider exploring.
1.If you know the relative location of file_2 with respect to file_1, you can construct the path dynamically using fullfile. This method is useful when the directory structure is consistent but the absolute path may vary.
relativePath = fullfile('..', 'otherDirectory', 'file_2.ext');
data = readmatrix(relativePath); % Use the appropriate function for your file type
2. Allow users to specify the path. This method is particularly useful when sharing your code with others who may have a different directory structure.
userPath = input('Enter the path to file_2: ', 's');
data = readmatrix(userPath);
3. For a more interactive approach, especially in desktop environments, use uigetfile to open a file dialog that allows users to navigate to and select file_2.
[file, path] = uigetfile('*.*', 'Select file_2');
if isequal(file, 0)
disp('User selected Cancel');
else
fullPath = fullfile(path, file);
data = readmatrix(fullPath);
end
4. For projects shared across multiple users, consider using a configuration file that specifies paths. Users can edit this file to set their paths.
config.txt
path_to_file_2 = /path/to/file_2.ext
MATLAB Code
config = readtable('config.txt', 'ReadVariableNames', false, 'Delimiter', '=');
file2Path = strtrim(config{1,2}{1});
data = readmatrix(file2Path);
I hope it helps to resolve your issue.

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by