Trouble importing similar .txt files using readtable (error: all lines must have the same number of delimiters)

26 visualizaciones (últimos 30 días)
Hello,
I'm trying to import several .txt files using readtable in the following code;
n=input('How many spectrums to analyse? ');
for i=1:1:n
filename=uigetfile;
opts = detectImportOptions(filename);
opts.Delimiter=',';
T=readtable(filename);
T1=T{1:end-1,1}; T1=str2double(T1); T2=T{1:end-1,2}; % removing the last row containing '##END=, NaN' and converting into double vectors
eval(['nx_' num2str(i) '=T1;']) % assignment
eval(['ny_' num2str(i) '=T2;']) % assignment
j=1; while (filename(j)~='_'); leg(j)=filename(j); j=j+1; end % Extracting the name of Mineral from filename
eval(['legends{' num2str(i) '}=leg;']) % Storing legend names for later use
end
This works for some of the files, but shows the following error for some files inspite of the fact that the files are similar. One file that causes error is attached with another one that works fine.
Error using readtable (line 216)
Reading failed at line 2289. All lines of a text file must have the same number of delimiters. Line 2289 has 0 delimiters, while preceding lines have 1.
Note: readtable detected the following parameters:
'Delimiter', ',', 'HeaderLines', 10, 'ReadVariableNames', false, 'Format', '%f%f'
It is true that the last line has no delimiter, but it works with other files by inserting a 'NaN' in the second column of the last line. Please help me identify where the problem is or suggest me a different way to import the data from these .txt files. This works with uiimport but I want the importing process to be independent (i.e. without any user interactions).
Thanks!

Respuesta aceptada

Akira Agata
Akira Agata el 31 de Jul. de 2019
I think the following way would be more stable.
% Read data
fid = fopen('Error.txt','r');
str = textscan(fid,'%s','Delimiter','\r');
str = str{1};
fclose(fid);
% Delete the lines which starts with '#'
idx = startsWith(str,'#');
str(idx) = [];
% Split each column and convert to double
data = str2double(split(str));
% Store in table
T = array2table(data);

Más respuestas (0)

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by