How to access text files from many subfolders within a folder?
조회 수: 8 (최근 30일)
이전 댓글 표시
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
채택된 답변
Nikhil Negi
2018년 5월 18일
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
추가 답변 (1개)
Jan
2018년 5월 18일
편집: Jan
2018년 5월 18일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!