我真的需要有关将多个CSV文件合并到单个文件中的帮助。第一次,我设法运行此代码:
%% Merge multiple CSV files into one CSV file
myDir = uigetdir % gets directory from any folder
d=dir(fullfile(myDir,'*.csv')); % retrieve the files
fido=fopen(fullfile('finalCSVnew.csv'),'w'); % open output file to write
for i=1:length(d)
fidi=fopen(fullfile(myDir,d(i).name)); % open input file
fwrite(fido,fread(fidi,'*char')); % copy to output
fclose(fidi); % close that input file
end
fido=fclose(fido); clear fid* d % close output file, remove temporaries
原来我必须更改“myDir”的命令,这样才能在一个文件夹中选择多个文件,而不是一个文件夹中需要处理的所有文件。所以我将上面的代码更改为:
%% Merge multiple CSV files into one CSV file
myDir = uigetfile('*.csv','Select the data file','MultiSelect','on'); % gets directory from any folder
d=fullfile(myDir,'*.csv'); % retrieve the files
fido=fopen(fullfile('finalCSVnew.csv'),'w'); % open output file to write
for i=1:length(d)
fidi=fopen(fullfile(myDir,d(i).name)); % open input file
fwrite(fido,fread(fidi,'*char')); % copy to output
fclose(fidi); % close that input file
end
fido=fclose(fido); clear fid* d % close output file, remove temporaries
并且出现错误消息
来自非结构数组对象的结构内容引用。
答案 0 :(得分:1)
您的第二个代码中存在一些错误:
uigetfile
会在char
字符串中返回其名称,如果您选择多个文件,则会在cellarray
中返回其名称,因此您必须管理它。您可以使用函数class
进行检查fopen(fullfile('finalCSVnew.csv'),'w')
时,您未在path
的电话中提供fullfile
因此似乎无用uigetfile
的返回值为0
您可以采用以下方式更新代码
% Call uigetfile by specifying file name and path as output
[f_name,f_path] = uigetfile('*.txt','Select the data file','MultiSelect','on'); % gets directory from any folder
% Check for file selection abort
if(~strcmp(class(f_name),'double'))
fido=fopen(fullfile(f_path,'finalCSVnew.txt'),'w'); % open output file to write
% check for the number of selected files
% if multiple file
if(strcmp(class(f_name),'cell'))
% Loop over the selected files
for i=1:length(f_name)
fidi=fopen(fullfile(f_path,f_name{i})); % open input file
fwrite(fido,fread(fidi,'*char')); % copy to output
fclose(fidi); % close that input file
end
else
fidi=fopen(fullfile(f_path,f_name)); % open input file
fwrite(fido,fread(fidi,'*char')); % copy to output
fclose(fidi); % close that input file
end
fido=fclose(fido); clear fid* d
else
disp('File Selection Aborted')
end
替代解决方案
如果您只想合并某些文件,可以使用system
函数调用DOS
命令。
% Call uigetfile by specifying file name and path as output
[f_name,f_path] = uigetfile('*.txt','Select the data file','MultiSelect','on'); % gets directory from any folder
% Check for file selection abort
if(~strcmp(class(f_name),'double'))
fido=fullfile(f_path,'finalCSVnew.txt'); % open output file to write
% check for the number of selected files
% if multiple file
if(strcmp(class(f_name),'cell'))
% Loop over the selected files
for i=1:length(f_name)
system(['type ' fullfile(f_path,f_name{i}) ' >> ' fido])
end
else
system(['copy ' fullfile(f_path,f_name) ' ' fido])
end
else
disp('File Selection Aborted')
end
希望这有帮助,
Qapla'