textscan error only in loop: "Invalid file identifier. Use fopen to generate a valid file identifier"

1 回表示 (過去 30 日間)
Hi,
I am receiving textscan error when I create a loop to process and write my files. If I run each file individually without a loop, it works without any problem. If anyone knows what will be the reason of it?
"Error using textscan.Invalid file identifier. Use fopen to generate a valid file identifier."
[fname,pname] = uigetfile("MultiSelect","on",'*.dat')
fname=[pname, fname];
if isequal(fname,0)
disp('User selected Cancel');
else
disp(['User selected ', fullfile(pname, fname)]);
end
for k = 1 : length(fname)
fprintf('Now reading file %s\n', fname{k});
fid=fopen(fname{k},'r');
F=textscan(fid,'%f','HeaderLines',17);
Temp=F{1,1}
T_out = timetable(datetime(2018,1,17,0,0,10*(0:size(Temp,1)-1)'),Temp);
time_array=datetime("29-May-2018 00:00:00", "InputFormat","dd-MMM-uuuu HH:mm:ss")
summerstart=find(T_out.Time=="29-May-2018 00:00:00")
Tsummer=T_out([summerstart]:end,:)
[filepath,name,ext] = fileparts(fname)
writetimetable(Tsummer,[name 'r.csv'])
end
Thanks a lot!

採用された回答

Stephen23
Stephen23 2022 年 4 月 21 日
編集済み: Stephen23 2022 年 4 月 21 日
This will not work as you require:
fname=[pname, fname];
Instead you should use FULLFILE, to correctly handle the file separator character, for example:
[fnc,fpt] = uigetfile("MultiSelect","on",'*.dat');
if isequal(fnc,0)
return
end
for k = 1:numel(fnc)
fprintf('Now reading file %s\n', fnc{k});
fnm = fullfile(fpt,fnc{k}); % better to use FULLFILE
fid = fopen(fnm,'r');
tmp = textscan(fid,'%f','HeaderLines',17);
fclose(fid); % you need to FCLOSE every file
.. etc
end
  1 件のコメント
Cakil
Cakil 2022 年 4 月 21 日
Thank you very much, I could not make a connection with fname=[pname, fname] and the textscan error but it works perfectly now :)

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

その他の回答 (1 件)

Jonas
Jonas 2022 年 4 月 21 日
編集済み: Jonas 2022 年 4 月 21 日
use fclose(fid) at the end of the for loop
sometimes, if using a script a file remains open and you may not have the identifier anymore. in this case use fclose('all')
  1 件のコメント
Cakil
Cakil 2022 年 4 月 21 日
Thank you, I tried both fclose(fid) and fclose('all') but still receiving the same error.

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

カテゴリ

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

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by