MATLAB:如何从.txt文件中加载文件名列表



filelist.txt包含一个文件列表:

/path/file1.json
/path/file2.json
/path/fileN.json

是否有一个(简单的(MATLAB 命令可以接受文件列表.txt并将每个文件读取为字符串并将每个字符串存储到单元格数组中?

只需使用readtable,要求它完整地阅读每一行。

>> tbl = readtable('filelist.txt','ReadVariableNames',false,'Delimiter','n');
>> tbl.Properties.VariableNames = {'filenames'}
tbl =
3×1 table
filenames     
__________________
'/path/file1.json'
'/path/file2.json'
'/path/fileN.json'

然后访问循环中的元素

for idx = 1:height(tbl)
this_filename = tbl.filenames{idx};
end

这个问题对于标准函数来说有点具体。但是,通过结合两个功能很容易做到:

首先,您必须打开文件:

fid = fopen('filelist.txt');

接下来,您可以逐行阅读:

line_ex = fgetl(fid)

此功能包括一个计数器。如果下次调用该函数,它将读取第二行,依此类推。您可以在此处找到更多信息。

整个代码可能如下所示:

%   Open file
fid = fopen('testabc');
numberOfLines = 3;
%   Preallocate cell array
line = cell(numberOfLines, 1);
%   Read one line after the other and save it in a cell array
for i = 1:numberOfLines
line{i} = fgetl(fid);
end
%   Close file
fclose(fid);

为此,将 for 循环替换为 while 循环:

i=0;
while ~feof(fid)
i=i+1
line{1} = fgetl(fid)
end

while 循环的替代方法:检索行数并在 Caduceus 的 for 循环中使用:

%   Open file
fid = fopen('testabc');
numberOfLines = numlinestextfile('testable');  % function defined below
%   Preallocate cell array
line = cell(numberOfLines, 1);
%   Read one line after the other and save it in a cell array
for i = 1:numberOfLines
line{i} = fgetl(fid);
end
%   Close file
fclose(fid);

自定义功能:

function [lineCount] = numlinestextfile(filename)
%numlinestextfile: returns line-count of filename
%   Detailed explanation goes here
if (~ispc) % Tested on OSX
evalstring = ['wc -l ', filename];   
% [status, cmdout]= system('wc -l filenameOfInterest.txt');
[status, cmdout]= system(evalstring);
if(status~=1)
scanCell = textscan(cmdout,'%u %s');
lineCount = scanCell{1}; 
else
fprintf(1,'Failed to find line count of %sn',filenameOfInterest.txt);
lineCount = -1;
end
else
if (~ispc)     % For Windows-based systems
[status, cmdout] = system(['find /c /v "" ', filename]);
if(status~=1)
scanCell = textscan(cmdout,'%s %s %u');
lineCount = scanCell{3};
disp(['Found ', num2str(lineCount), ' lines in the file']);
else
disp('Unable to determine number of lines in the file');
end
end
end

最新更新