How to access text files from many subfolders within a folder?
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Vishvendra Bhanu
am 18 Mai 2018
Bearbeitet: Jan
am 21 Mai 2018
Hey! I want to access a main folder which has 44 subfolders. Each subfolder contains a txt file. I want to run a loop to open that text file and store its last line. Could you please help me with that? So far I have reached to this point:
if true
mainFolder = 'FEMA_P695_Far_Field_Long';
d = dir(mainFolder);
idxs = [d(:).isdir]';
names = {d(:).name}';
folders = names(idxs);
folders(ismember(folders,{'.','..'})) = [];
for k = 1:numel(folders)
myFolder = folders{1,1}(k);
cd folders{1,1}(k);
m = load('ida_curve.txt');
end end This is an incomplete code. From this I have a all my subfolders in the 'folders'. I dont know how to go ahead and open the text file within each subfolder and then how to write only the last line of the 'ida_curve.txt' file in a new file. Could you please help me with this? I am trying to learn new things in MATLAB.
0 Kommentare
Akzeptierte Antwort
Nikhil Negi
am 18 Mai 2018
Hello Vishvendra,
from what i can deduce from your description, you already have a list of folders you need. I will suggest you define a function that takes a file as input and extracts the last line of that file.
You can do that by defining the function that iterates through the text file and checks if the next line to current line is equal to '-1' this way you will know that the current line is the last line of that text file and return it. you should use fgetl to read a text file line by line
then you can loop over the list of folders you have and get the last line of all the files
fgetl documentation - https://www.mathworks.com/help/matlab/ref/fgetl.html
0 Kommentare
Weitere Antworten (1)
Jan
am 18 Mai 2018
Bearbeitet: Jan
am 18 Mai 2018
mainFolder = 'D:\FEMA_P695_Far_Field_Long'; % Use absolute paths
mainList = dir(mainFolder);
subFolder = {mainList([mainList.isdir]).name};
subFolder(ismember(subFolder, {'.','..'})) = [];
Result = cell(1, numel(subFolder));
for iSub = 1:numel(subFolder)
File = fullfile(mainFolder, subFolder{iSub}, 'ida_curve.txt');
Str = fileread(File);
CStr = strsplit(Str, '\n');
Result{iSub} = CStr{end};
end
Since Matlab R2016b, dir can work recursively:
mainFolder = 'D:\FEMA_P695_Far_Field_Long'; % Use absolute paths
fileList = dir(fullfile(mainFolder, '**', 'ida_curve.txt'));
Result = cell(1, numel(FileList));
for iFile = 1:numel(FileList)
File = fullfile(FileList(iFile).folder, FileList(iFile).name);
Str = fileread(File);
CStr = strsplit(Str, '\n');
Result{iSub} = CStr{end};
end
2 Kommentare
Siehe auch
Kategorien
Mehr zu File Operations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!