Read a Special Text File
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I was wondering if there is a quick way to read the following text file sample where the first data line starts with a bracket. I would like to avoid the hassle of manually removing the bracket from every file I obtain. I use the following command for now after I remove the bracket.
Thanks.
data = textscan(Fopen, '%d %f %d %d %d;', 'HeaderLines',2)
file.txt
1 Kommentar
Stephen23
am 23 Apr. 2022
A simple and very efficient approach would be to simply define the square bracket as whitespace, which you can do using TEXTSCAN's WHITESPACE option. Another good approach would be to use a fixed-width import via READTABLE.
Using STR2NUM is not very efficient.
Akzeptierte Antwort
Stephen23
am 23 Apr. 2022
Bearbeitet: Stephen23
am 23 Apr. 2022
Here are two much more efficient approaches.
The first is exactly like you are doing now, just adding the WHITESPACE option to efficiently ignore the square bracket:
fnm = 'textfile.txt';
fmt = '%d%f%d%d%d;';
opt = {'HeaderLines',2, 'Whitespace',' \t['};
fid = fopen(fnm,'rt');
data = textscan(fid, fmt, opt{:})
fclose(fid);
The second is to import the file as table, which has headers and may be more convenient to access:
opt = detectImportOptions(fnm, 'FileType','fixedwidth', ...
'VariableWidths',[6,9,16,16,16], 'VariableNamesLine',1, ...
'VariableNamingRule','preserve', 'Range',3, 'Whitespace',' [', ...
'ExtraColumnsRule','ignore');
tbl = readtable(fnm,opt)
Weitere Antworten (2)
Voss
am 22 Apr. 2022
Bearbeitet: Voss
am 22 Apr. 2022
% read file into character vector data
data = fileread('textfile.txt');
% remove the first two lines
idx = find(data == newline(),2);
data(1:idx(end)) = [];
% convert to numeric
M = str2num(data);
% show some results
format long
disp(M(1:10,:));
disp(M(end-9:end,:));
2 Kommentare
Siehe auch
Kategorien
Mehr zu Data Import and Export finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!