How to use the load function to open and read a .txt file?

21 次查看(过去 30 天)
I have a macbook air and I made a .txt file using Word. I imported it into Matlab and now I want to load it using the load function but Matlab says
"Error using load
Unable to read file 'FILENAME'. No such file or directory."
I imported the file and it is in my workspace so why is the load function now working?
  18 个评论
Giuseppe Inghilterra
编辑:Giuseppe Inghilterra 2020-2-15
Try:
load('C:\Users\sarahabraham\Desktop\HW2.txt')
and of course HW2.txt file is in your desktop.
Sorry, I see that you have already solved your problem ;)
Walter Roberson
Walter Roberson 2020-2-15
A filename of the form /Users/NAME/desktop is most likely a Mac, in which case \ between path components would not work, and C: drive would not work.
Interestingly, on Windows, you can use / in paths -- so if such a file existed, 'C:/Users/sarahabraham/Desktop/HW2' would be valid. This suggests that for portability, if you do not code in terms of fullfile(), that you are better off coding in terms of /

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2020-2-15
Sarah, The problem was that the file was not in the same folder as your script (if you were running an m-file) or your current folder (if you were running from the command line). So you need to construct the full filename accurately, using the full folder of where it lives, plus the extension of the file. Try this more robust code:
folder = 'C:\Users\sarahabraham\Desktop\';
fullFileName = fullfile(folder, 'BME330HW2.txt');
if ~isfile(fullFileName)
warningMessage = sprintf('File not found:\n%s\nWhen the next dialog box comes up, please locate it.', fullFileName)
uiwait(errordlg(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 ~exist(startingFolder, 'dir')
% 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, '*.*'); % Can use *.txt if you want only text files to show up.
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
end
s = load(fullFileName)
Paste this into a script and run it. Now, no matter where the script lives, it will first try to try to find the file called
'C:\Users\sarahabraham\Desktop\BME330HW2.txt' % Change to different filename, if desired.
If that file does not exist, then it will bring up a dialog box asking the user to find the file she wants to read in.
Hope that helps.

类别

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