简体   繁体   中英

I want to export the name of multiple matlab files into a .csv

I want to use a for loop to export the names of a folder of .mat files into one .csv file by row.

I am trying to use xlswrite, but don't understand how to access the filename of the .mat files.

I am working with to write them to the csv.

xlswrite(fullfile(dest_dir,'result.csv'), FILENAME HERE, ['A' num2str(i)]);

To get your filename, load the files using dir command, read them individually in your for loop, and then write them to file. (I think I already posted something like this?) Here is the prototype:

files = dir('*.mat');               % obtain all files with .mat extenstion
fid = fopen('result.csv','a');   

for k = 1:length(data)
    filename = files(k).name;       % get the filename
    fprintf(fid, '%s,\n', filename);
end

fid = fclose(fid);

Unfortunately, you cannot just save the file names as strings in a cell and write it as you might a matrix using say csvwrite , so you can just do this.

xlswrite creates a excel workbook

With dir command you can get a structure whose one of field is name of file.

Using simple file IO function your requirement can be met.

I think either of this will do what you need:

fid=fopen('result.csv','wt');

files=dir('*.mat');
x={files(:).name};

csvFun = @(str)sprintf('%s,',str);
xchar = cellfun(csvFun, x,'UniformOutput', false);
xchar = strcat(xchar{:});
xchar = strcat(xchar(1:end-1),'\n');

fprintf(fid,xchar);

fclose(fid);

Or

If you just need .mat names in a column form:

fid=fopen('result.csv','wt');

files=dir('*.mat');
x={files(:).name};

[rows,cols]=size(x);

for i=1:rows
  fprintf(fid,'%s,',x{i,1:end-1});
  fprintf(fid,'%s\n',x{i,end});
end

fclose(fid);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM