创建一个文件夹,而不是在其中写入许多文本文件



我想创建一个名为"all"的文件夹,然后我想在"all"中创建和写入许多文本文件。文本文件的名称为 x1.txt、x2.txt、x3.txt 等等。这是我的方法,但不知何故失败了:

    folderName  = all;       
    mkdir(folderName);
    temp = ['x', num2str(k), '.txt'];
    fid2 = fopen('x.txt', 'w');
    fprintf(fid2, '%sn', [folderName/temp '/' M{:}]); % M is a string, that I want to write in the text file
    fclose(fid2);

试试这个 -

folderName = 'all';
mkdir(strcat(folderName,filesep,'temp'));
N = 10; %%// Number of files needed
for k = 1:N
    temp = ['x', num2str(k), '.txt'];
    pathname1 = strcat(pwd,filesep,folderName,filesep,'temp',filesep,temp);%%// creates the temp directory in the working directory.
    fid1 = fopen(pathname1, 'w');
    fprintf(fid1, '%sn',M{:});
    fclose(fid1);
end

因此,x1.txtx2.txtx3.txt等文件将在目录内创建,temp在目录all内创建,all在工作目录中。

如果您想在其他地方all创建此目录,请在开头提及folderName的完整路径并编辑pathname1创建,如下所示 -

pathname1 = strcat(folderName,filesep,'temp',filesep,temp);

最新更新