MATLAB Answers

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

106 views (last 30 days)
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
opts = detectImportOptions(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
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).


Sign in to comment.

Accepted Answer

Akira Agata
Akira Agata on 31 Jul 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};
% 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);

More Answers (0)

Sign in to answer this question.