How to upload csv. files from multiple folders

조회 수: 4 (최근 30일)
Ill ch
Ill ch 2019년 10월 11일
편집: Ill ch 2019년 10월 12일
Dear Matlab users,
I want to automize my program by uploading automatic csv. files from different folders. For example:
I have 15 folders and each folder has 4 csv files. Currently in my program i am uploading for each cycle(for loop) 4 csv. files...and running and getting results similarly for second cycle again i am uploading from second folder 4 csv files and running and so on for 15 times. Can anybody help me ? Attached my codes
mainFolder = uigetdir(); % Selectyour Main folder
[~,message,~] = fileattrib([mainFolder,'\*']);
fprintf('\n There are %i total files & folders.\n',numel(message));
allExts = cellfun(@(s) s(end-2:end), {message.Name},'uni',0); % Get exts
CSVidx = ismember(allExts,'csv'); % Search ext for "CSV" at the end
CSV_filepaths = {message(CSVidx).Name}; % Use CSVidx to list all paths.
fprintf('There are %i files with *.CSV exts.\n',numel(CSV_filepaths));
Total_Files = 1:numel(CSV_filepaths);
for Folder=1:numel(Total_Files)/2
[filenames pathname]=uigetfile('*.CSV','MultiSelect', 'on');
if isa(filenames,'cell')
name_order=0;
ind_order=0;
for i=1:max(size(filenames))
name_order=[name_order str2num(filenames{i}(10:end-4))];
ind_order=[ind_order i];
end
name_order=[name_order(2:end);ind_order(2:end)];
name_order_sorted=sortrows(name_order')';
name_ind=0;
for i=name_order_sorted(2,:)
name_ind=name_ind+1;
filenames_sorted{name_ind}=filenames{i};
end
filenames=filenames_sorted;
for i=1:max(size(filenames))
data=importdata([pathname filenames{i}]);
data=data.data;
files(i).name=filenames{i};
files(i).data=data;
end
elseif isa(filenames,'char')
data=importdata([pathname filenames]);
data=data.data;
files.name=filenames;
files.data=data;
else
error('No files selected !');
end
for i= 1:max(size(files))
display(files(i).name)
data=files(i).data;
My_data_t(:,1)=data(:,1)
My_data(:,2)=data(:,2)
end
end

답변 (1개)

prasanth s
prasanth s 2019년 10월 11일
편집: prasanth s 2019년 10월 11일
to automate the file and folder access operations, do not use 'uigetfile' or 'uigetdir' functions.
use 'dir' function to get the file and folder names of any directory.
D=dir('E:\folder');
to get all 'csv' filenames in 'myfolder'
F=dir('myfolder\*.csv')
loop through the output struct array 'F' and get the filenames
  댓글 수: 2
Ill ch
Ill ch 2019년 10월 11일
Thank you very much
Ill ch
Ill ch 2019년 10월 12일
편집: Ill ch 2019년 10월 12일
Hi Prasanth
With your suggested code i am not getting filenames. I have 13 folders in one main folder. each 13 folder has 4 csv. files
mainFolder =dir('C:\MATLAB\e'); % Selectyour Main folder
F=dir('C:\MATLAB\e.csv');

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Adding custom doc에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by