I want to export data to txt file in Loop

13 ビュー (過去 30 日間)
The boy
The boy 2023 年 2 月 1 日
コメント済み: The boy 2023 年 2 月 3 日
files = dir('*.txt');
N =length(files);
for i=1:N
data = readtable(files(i).name);
data = removevars(data, {'Var9','Var10'});
% save to txt file
newtxt = table2cell(finalfile(:,1:9));
writecell(newtxt,'newfile.txt','Delimiter','tab');
type newfile.txt
end
*** my code above is try to remove some columm in a txt file, I have 30 txt file like that need to work in a LOOP.
Everytime I write the txt file, the new file is overwritten in the same file name, I do not know how to write the txt file with using LOOP . Please help me to fix the code again. Thank you

採用された回答

Stephen23
Stephen23 2023 年 2 月 1 日
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.txt'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
D = readtable(F);
D = removevars(D, {'Var9','Var10'});
% new filename
[~,F,E] = fileparts(S(k).name);
F = sprintf('%s_new%s',F,E);
% save to txt file
newtxt = table2cell(finalfile(:,1:9));
writecell(newtxt,F,'Delimiter','tab');
end
  1 件のコメント
The boy
The boy 2023 年 2 月 3 日
Thanks Stephen23, I learned it . Your code work well!

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

その他の回答 (1 件)

Jeremy Hughes
Jeremy Hughes 2023 年 2 月 2 日
If you want to write the data to one file, this should work
for i=1:N
data = readtable(files(i).name);
% Assuming you're removing data you don't need (and that Var9 Var10 are # 9 and 10), this is the most concise way.
writetable(data(:,1:8),'newfile.txt','Delimiter','\t','WriteMode','append');
end
If you want do write to different files:
mkdir("newplace")
for i=1:N
data = readtable(files(i).name);
newname = fullfile("./newplace","new_"+files(i).name);
writetable(data(:,1:8),newname,'Delimiter','\t');
end
  1 件のコメント
The boy
The boy 2023 年 2 月 3 日
thanks Jeremy, this is good to learn from you.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by