Trouble reading in formatted text file
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jenny May
el 21 de Jun. de 2016
Editada: Shameer Parmar
el 22 de Jun. de 2016
Hi, I am trying to read in a formatted text file of unknown size. An example of the data I want to read in is shown below:
*lines 1-3: blank
*lines 4-6: useless text
*line 7: string string string double %(this line should be read into Settings)
*line 8: useless text
*lines 9-12: string double double string %(this line should be read into AlarmData)
*lines 13-16: blank
*line 17: string string %(this line should be read into Time)
This pattern then repeats throughout the entire file. My first thought was to determine the number of lines in the file so I used this code:
FileID= fopen(filename);
%Code to find number of lines in the file
assert(FileID~= -1, 'Could not read: %s', filename);
x= onCleanup(@() fclose(FileID));
count=0;
while ~feof(FileID)
count= count+sum(fread( FileID, 16384, 'char')==char(10));
end
fclose(FileID)
%code to determine number of data runs
num_data_runs=count/17;
I then try to loop through the file with textscan commands to read in the data to appropriate cells
FileID= fopen(filename);
iter=1;
while(iter<=num_data_runs)
Settings(iter,1:4)= textscan(FileID, '%s%s%s%f',1, 'headerLines', 6);
AlarmData(iter,1:4)= textscan(FileID, '%s %f %f %s',4, 'headerLines', 2);
Time(iter,1:2)= textscan(FileID, '%s%s', 1, 'headerLines', 4);
iter=iter+1;
end
fclose(FileID)
The result of this code is a 3x4 cell of AlarmData, a 3x4 cell of Settings, and a 3x2 cell of Time. The first row in all of these cells is what I intended them to be, but the other rows are all containing the wrong data from the file. Any thoughts?
Thanks
0 comentarios
Respuesta aceptada
Shameer Parmar
el 21 de Jun. de 2016
Consider you have text file with name 'Data.txt'.. then
Following command will give you all data present in text file.
Data = textread('Data.txt', '%s', 'delimiter', '')
and then..
NumberOfRows = length(Data);
to read the data row wise..
for count = 1:NumberOfRows
RowData = Data{count};
% add logic to perform any action on RowData.
end
2 comentarios
Shameer Parmar
el 22 de Jun. de 2016
Editada: Shameer Parmar
el 22 de Jun. de 2016
Yes.. it will work for any text file of more than 1,00,000 lines of code..I already tried it...before posting my answer... :)
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!