file path error in matlab

75 views (last 30 days)
ali hassan
ali hassan on 26 Jan 2022
Commented: Image Analyst on 27 Jan 2022
when i am running a command in matlab, it says:
>> a=readtable('111..txt','PreserveVariableNames',true)
Error using readtable
Unable to find or open '111..txt'. Check the path and filename or file permissions.
but once i change the path, problem is resolved. can my code not work with any path? because i am making a GUI and i want it to run the command,nomatter where the path is

Accepted Answer

Image Analyst
Image Analyst on 26 Jan 2022
It will work with any path as long as that file exists, which yours does not. Are you sure it has two dots in it? That would be unusual. Try this:
fullFileName = fullfile(pwd, '111..txt')
if ~isfile(fullFileName)
warningMessage = sprintf('File not found:\n%s\n\nOn the next screen, select a file.', fullFileName)
uiwait(warndlg(warningMessage))
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
if ~isfolder(startingFolder)
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
end
t = readtable('111..txt','PreserveVariableNames',true)
  2 Comments
ali hassan
ali hassan on 27 Jan 2022
i tried this but it is giving this error.
Error using readtable (line 318)
Unable to find or open '111..txt'. Check the path and filename or file permissions.
Image Analyst
Image Analyst on 27 Jan 2022
Sorry, it should use fullFileName in readtable(), not the hard coded filename.
fullFileName = fullfile(pwd, '111..txt')
if ~isfile(fullFileName)
warningMessage = sprintf('File not found:\n%s\n\nOn the next screen, select a file.', fullFileName)
uiwait(warndlg(warningMessage))
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
if ~isfolder(startingFolder)
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
end
t = readtable(fullFileName,'PreserveVariableNames',true)

Sign in to comment.

More Answers (0)

Categories

Find more on Search Path in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!