关于将多个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有一条错误信息
来自非结构数组对象的Struct内容引用。
发布于 2017-10-29 09:15:40
在第二个代码中有一些错误:
uigetfile将在char字符串中返回其名称,如果选择多个文件,则它们的名称将在cellarray中返回,因此必须对其进行管理。您可以使用函数class来检查它。fopen(fullfile('finalCSVnew.csv'),'w')的调用中,您没有在对fullfile的调用中提供path,因此它似乎毫无用处。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')
endhttps://stackoverflow.com/questions/46997924
复制相似问题