代码之家  ›  专栏  ›  技术社区  ›  maximusdooku

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

  •  3
  • maximusdooku  · 技术社区  · 10 年前

    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 回复  |  直到 10 年前
        1
  •  3
  •   Suever    10 年前

    您可以使用检查文件是否存在 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
    
        2
  •  2
  •   reas0n    10 年前

    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
    
        3
  •  0
  •   saastn    10 年前

    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