【问题标题】:Loop over a cell array if file exists in folder and print to new document如果文件夹中存在文件,则循环遍历单元格数组并打印到新文档
【发布时间】:2019-01-08 10:46:51
【问题描述】:

我想在读取工作中的文件时循环一个单元格数组 文件夹。如果该文件存在,则创建并打开名为 testcase.txt 的新文件 打印声明。如果该文件在工作文件夹中不存在,则什么也不做 并继续下一次迭代。

这是搜索一个文件的示例

fid=fopen('testcase.txt','w');

if exists('abc.txt','file')
    abc.txt = 1;
    fprintf('test case successful');
else
    abc.txt = 0;
end

fclose(fid);

这是一个扩展到多个案例的元胞数组示例,如下所示 我似乎无法让它正常运行。有人可以帮我得到这个 循环工作?

extension = {'abc.txt' 'def.txt' 'ght.txt'};
convertedfile = [abc.txt def.txt ght.txt];

fid=fopen('testcase.txt','w');

for i = extension
    if exist(['''' convertedfile ''''],'file')
        i = 1;
        fprintf('test case successful');
    else
        i = 0;
    end
end

fclose(fid);

【问题讨论】:

    标签: matlab for-loop exists cell-array


    【解决方案1】:

    您正在寻找这样的东西吗?

    extension = {'abc.txt' 'def.txt' 'ght.txt'};
    % convertedfile = [abc.txt def.txt ght.txt];
    
    fid=fopen('testcase.txt','w');
    
    for i = 1:length(extension)
        if ~exist(extension{i},'file')
    
            fprintf(fid,'test case successful\n');
        end
    end
    fclose(fid);  
    

    此外,您可以使用以下方法打印成功的文本文件:

    fprintf(fid,'%s: test case successful\n',extension{i});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2012-02-17
      相关资源
      最近更新 更多