MATLAB Answers

0

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

Asked by Vineeth Prekar K on 30 Jul 2019
Latest activity Commented on by Vineeth Prekar K on 1 Aug 2019
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!

  0 Comments

Sign in to comment.

Products


Release

R2019a

1 Answer

Answer by Akira Agata
on 31 Jul 2019
 Accepted Answer

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);

  1 Comment

Sign in to comment.