Resolved: Need help for using textscan to read a csv file

조회 수: 14 (최근 30일)
Leon
Leon 2013년 8월 8일
Below is my code. I could not find any issues with that. But the results "tmp" are always empty {0x70 cell}.
Please help. Thanks.
====== Code =======
fid = fopen('testfile.csv', 'rt');
formatspec = [repmat('%s ', 1, 70) '%*[^\n]'];
tmp = textscan(fid, formatspec, 1, 'delimiter', ',', 'collectoutput', true, 'headerlines', 16);
fclose(fid);
======= One row of the data file ========== 09FA20010524,09FA20010524,1,2.00105E+17,1,24,2,20010525,0,-44.429,179.9582,1011,989,1000.8,4.531,-999,9,34.307,2,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,2.781,2,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,9,-999,-999,-999,-999,-999,4.45259,27.1871,31.7778,36.2656,40.6526,44.9407
  댓글 수: 4
Walter Roberson
Walter Roberson 2013년 8월 9일
Could you show us a sample line? The 17th line from the csv ?
Leon
Leon 2013년 8월 9일
I just added a sample line as above. Thanks.

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2013년 8월 9일
>> s='09FA20010524,09FA20010524,...,31.7778,36.2656,40.6526,44.9407';
>> fmt = [repmat('%s ', 1, 70) '%*[^\n]'];
>> textscan(s, fmt, 1, 'delimiter', ',', 'collectoutput', true)
ans =
{1x70 cell}
>> ans{1}
ans =
Columns 1 through 7
'09FA20010524' '09FA20010524' '1' '2.00105E+17' '1' '24' '2'
Columns 8 through 14
'20010525' '0' '-44.429' '179.9582' '1011' '989' '1000.8'
...
Columns 68 through 70
'44.9407' [] []
>> length(findstr(s,','))
ans =
67
Your problem is the last -- there are only 68 fields, not 70 at least in the above record and that combined w/ the last '%*[^\n]' in the format string causes the failure on subsequent lines. Also, lose the extra blank in the format string; it instructs textscan() to try to match an explicit blank of which there are none in the file--I'm a little surprised that didn't cause a failure.
Just use
fmt = repmat('%s', 1, 68);
should be all you need.
Check the input file for consistency in number of columns/record, though, too.
  댓글 수: 1
Leon
Leon 2013년 8월 9일
편집: Leon 2013년 8월 9일
Thank you so much, Dpb. That solved my problem. I appreciate your time in helping me out very much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by