Importing text files using uigetfile
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm attempting to import some data from a text file. When I use the Import Data tool and then use the generate script function it works fine. (snippet below)
filename = 'C:\Documents and Settings\gavinbr\Desktop\Muirake\test files\NL_001_OCT_Lp _0001_0001.rnd';
delimiter = ',';
startRow = 3;
formatSpec = '%*s%*s%*s%*s%*s%*s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false);
However I wish to replace the first line with:
[filename,pathname] = uigetfile('*.rnd','Select the rnd file to process','Multiselect','on');
So I can select the files I wish to process each time and select more than one file each time. However it returns the following error:
Error using textscan Invalid file identifier. Use fopen to generate a valid file identifier.
Error in importscript (line 33)
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false);
Does anyone know how I can get around this?
Thanks in advance
0 commentaires
Réponses (2)
Azzi Abdelmalek
le 22 Juin 2015
Check the value of fileID
fileID = fopen(filename,'r')
If fileID is equal to -1, that means you can't open the file for many reasons, maybe the file doesn't exist.
5 commentaires
Stephen23
le 23 Juin 2015
Modifié(e) : Stephen23
le 23 Juin 2015
Probably you are only providing the filename to fopen, and not the path as well. If you do not supply any path information, then fopen will only look in the current directory. Consider the difference:
fid = fopen('my_work.txt','rt');
looks for a file called my_work.txt located in the current directory. Whereas
strP = 'C:\Users\Anna\Results';
strF = 'my_work.txt';
fid = fopen(fullfile(strP,strF),'rt');
also provides the directory location. You should look at Jan Simon's answer, which shows you how to use this in a complete example, but basciyll you need to do this:
[filename,pathname] = uigetfile(...);
str = fullfile(pathname,filename);
fid = fopen(str,'rt');
... ETC
Jan
le 23 Juin 2015
Modifié(e) : Jan
le 23 Juin 2015
[filename, pathname] = uigetfile('*.rnd', 'Select the rnd file to process', 'Multiselect', 'on');
if isequal(filename, 0)
disp('User aborted reading of files.');
return;
end
for k = 1:length(filename)
aFile = fullfile(pathname, filename{k});
% Now perform the operation with this file. E.g. show its name:
disp(aFile);
fid = fopen(aFile, 'r');
if fid < 0
error('Cannot open file: %s', filename);
end
...
end
0 commentaires
Voir également
Catégories
En savoir plus sur Low-Level File I/O dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!