Batch process text files

3 ビュー (過去 30 日間)
alia
alia 2015 年 2 月 6 日
コメント済み: alia 2015 年 2 月 8 日
I am trying to save series of cells in a loop. I need to batch process text files having a 10 lines of both numbers and characters ( 12 12 34 54 rr). I am trying to save them in cell array so that i can access them later. The code I have written is giving error :
error : Error using textscan Invalid file identifier. Use fopen to generate a valid file identifier.
This code is working perfectly without the loop. Please help I am new to matlab. Is there any other better method of saving the files.
My code :
input_directory = 'd2/';
filelabels = dir([input_directory '*.txt']);
wav_label1 = cell(12,12);
wav_label2 = cell(12,12);
for i = 1: numel(filelabels)
fileName = filelabels(i).name;
fid = fopen(fileName);
results{i}= textscan(fid,'%f %f %f ........
%s','HeaderLines',2,'Delimiter',',','CollectOutput',1);
fclose(fid);
%testscan is giving output as a cell{{1,1}{1,2}} as I have numbers
%and characters both in text file
wav_label1{i} = results{1,1};
wav_label2{i} = results{1,2};
end
Thanks
  2 件のコメント
dpb
dpb 2015 年 2 月 6 日
The error indicates the file handle is invalid which means the fopen didn't succeed. Use the optional second output argument to see where the problem arises...
[fid,msg] = fopen(fileName);
if fid<0
error(['FOPEN: ' msg ' while opening: ' fileName])
end
Guillaume
Guillaume 2015 年 2 月 6 日
編集済み: Guillaume 2015 年 2 月 6 日
Or better, use the formatting facility of error:
if fid<0
error('FOPEN: %s while opening ''%s''', msg, fileName);
end
With any code that deals with entities external to your program (user input, file system, database, etc.), always be prepared to deal with unexpected failure.

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

採用された回答

Udit Gupta
Udit Gupta 2015 年 2 月 6 日
You can use -
fileName = [input_directory filelabels(i).name];
That should solve the issue.
  2 件のコメント
Guillaume
Guillaume 2015 年 2 月 6 日
編集済み: Guillaume 2015 年 2 月 6 日
That would probably solve the problem, but it is always good practice to check that a fopen succeeds.
It is also good practice to use path manipulation functions instead of string manipulation functions when dealing with path. In this case:
fileName = fullfile(input_directory, filelabels(i).name);
would be safer. You don't have to worry whether or not your path ends by a path separator, nor what that separator exactly is (so your code works on any platform).
alia
alia 2015 年 2 月 8 日
The code works now. Thanks a lot. You correctly pointed my mistake. Thanks a ton :)

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2015 年 2 月 6 日
I would say the most likely reason is that you do not have a subdirectory of the current working directory called "d2". You can use mkdir() to create it.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by