How to ignore or delete the last row of a text file when importing?

6 ビュー (過去 30 日間)
Al
Al 2015 年 5 月 31 日
コメント済み: Star Strider 2015 年 5 月 31 日
I am reading in data using textscan. Often times the last row of data is bad and throws an error. How can I ignore the last line? or is there code to delete the last row of data in the text file programmatically?

採用された回答

Star Strider
Star Strider 2015 年 5 月 31 日
It’s difficult to be specific without your file. If you know how many lines you want to read, you can set that limit as a parameter.
From the documentation:
  • C = textscan(fileID,formatSpec,N) reads file data using the formatSpec N times, where N is a positive integer. To read additional data from the file after N cycles, call textscan again using the original fileID. If you resume a text scan of a file by calling textscan with the same file identifier (fileID), then textscan automatically resumes reading at the point where it terminated the last read.
  2 件のコメント
Al
Al 2015 年 5 月 31 日
編集済み: Al 2015 年 5 月 31 日
I placed this code prior to texscan
fid = fopen('your_file.TXT','r');
fseek(fid, 0, 'eof');
chunksize = ftell(fid);
fseek(fid, 0, 'bof');
ch = fread(fid, chunksize, '*uchar');
nol = sum(ch == sprintf('\n')); % number of lines
fclose(fid)
Then I replaced the N in
C = textscan(fileID,formatSpec,N)
with
nol-2
This did it. Thank you.
Star Strider
Star Strider 2015 年 5 月 31 日
My pleasure!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2015 年 5 月 31 日
Put it in a try catch block. Look it up in the help. You can just have your catch block be empty if you want to ignore any errors.

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by