Clear Filters
Clear Filters

Execute script on multiple Files

2 views (last 30 days)
Nainpreet
Nainpreet on 13 Apr 2023
Commented: Nainpreet on 13 Apr 2023

Hey,
i have multiple folders, within every folder is a .txt file. I need to run a script on every .txt file independently and need the output in the same folder as the .txt file is.

  2 Comments
Stephen23
Stephen23 on 13 Apr 2023
The MATLAB approach:
P = 'absolute or relative path to where the subfolders are';
S = dir(fullfile(P,'*','*.txt'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
% your code here, to process file F
output = ..
G = fullfile(S(k).folder,'output.txt')
% save output data in file G
end
Nainpreet
Nainpreet on 13 Apr 2023
i tried to implement it, but it some how doesnt work. Does it also work with the import feature ? I attached my code

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 13 Apr 2023
Edited: Stephen23 on 13 Apr 2023
With many assumptions, e.g. that the required folders are all subfolders of one parent folder.
You should also pay attention to the advice you got for your prior questions, e.g.:
opts = delimitedTextImportOptions("NumVariables", 9, "Encoding", "UTF16-LE");
% Specify range and delimiter
opts.DataLines = [30, Inf];
opts.Delimiter = "\t";
% Specify column names and types
opts.VariableNames = ["Name", "Frequenz", "Var3", "Var4", "Var5", "Var6", "Var7", "Var8", "Var9"];
opts.SelectedVariableNames = ["Name", "Frequenz"];
opts.VariableTypes = ["double", "double", "string", "string", "string", "string", "string", "string", "string"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Specify variable properties
opts = setvaropts(opts, ["Var3", "Var4", "Var5", "Var6", "Var7", "Var8", "Var9"], "WhitespaceRule", "preserve");
opts = setvaropts(opts, ["Var3", "Var4", "Var5", "Var6", "Var7", "Var8", "Var9"], "EmptyFieldRule", "auto");
P = '\\DEDOSAN001\vol1\E\EMV\Kularia\Matlabprogramm\04_Messungen';
S = dir(fullfile(P,'*','Ergebnistabelle.txt'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
T = readtable(F, opts);
G = fullfile(S(k).folder,'RA1_AV.asc')
fid = fopen(G,'wt');
fprintf(fid, '%3.4f\t%f\n', [T.Name,T.Frequenz].');
fclose(fid);
end
  1 Comment
Nainpreet
Nainpreet on 13 Apr 2023
it works perfect thank you. Yeah im pretty new to all of this, but i try to keep it in mind :D

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!