如果文件不存在,如何从导入中跳过文件?

时间:2016-05-02 20:36:51

标签: matlab import

tarFileNames包含需要导入的所有文件的名称。某些文件可能不存在。如何跳过不存在的文件,以便循环不会因此错误而停止:

Error using imread (line 349)
File "C:\Users\xyz.tif" does not exist.

代码:

for m = 1:length(tarFileNames)
    tarConus = imread(tarFileNames{m});
    tarConus(end,:) = []; % Dropping last col and row from each page 
    tarConus(:,end) = [];
    tarAccum = plus(tarConus(select),tarAccum); 
end

3 个答案:

答案 0 :(得分:3)

您可以使用exist检查是否存在文件。请务必指定第二个输入参数,该参数指定您只想按该名称查找文件。

%// Determine all of the files that don't exist.
doesExist = cellfun(@(x)exist(x, 'file') == 2, tarFileNames);

%// File which do not exist
invalidNames = tarFileNames(~doesExist);

%// File which do exist
validNames = tarFileNames(doesExist);

%// Only loop through the ones that do exist
for m = 1:numel(validNames)     
    tarConus = imread(validNames{m});
    tarConus(end,:) = []; % Dropping last col and row from each page 
    tarConus(:,end) = [];
    tarAccum = plus(tarConus(select),tarAccum); 
end

答案 1 :(得分:2)

exist()可以检查文件是否存在。这应该做到:

for m = 1:length(tarFileNames)
    if exist(tarFileNames{m}, 'file')
        tarConus = imread(tarFileNames{m});
        tarConus(end,:) = []; % Dropping last col and row from each page 
        tarConus(:,end) = [];
        tarAccum = plus(tarConus(select),tarAccum);
    end 
end

答案 2 :(得分:0)

if exist(Name, 'file')如果文件存在则返回2,如果存在文件夹则返回7。

抱歉,目前没有matlab可供您编写和测试完整代码。

我想它应该是这样的:

for m = 1:length(tarFileNames)
    if exists(tarFileNames{m}, 'file')
       tarConus = imread(tarFileNames{m});
       tarConus(end,:) = []; % Dropping last col and row from each page 
       tarConus(:,end) = [];
       tarAccum = plus(tarConus(select),tarAccum); 
    else
    end
end