Import multiple text file with one header
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello everyone,
There are several questions and answers on the site; however, I have a bit of issue by combining several text files.
I have two text files, the first one with headers and the second one without.
I would like to merge them into one file, called 'data' preferably using cell2mat format, and also have a separate variable that shows the headers.
---------
file1.txt
a b c
1 2 3
4 5 6
file2.txt
7 8 9
10 11 12
---------
any help much appreciated!
Many thanks,
댓글 수: 0
답변 (3개)
Michael Haderlein
2014년 8월 11일
files=dir('test*.txt');
output='data.txt';
fidout=fopen(output,'w');
for cnt=1:length(files)
fprintf(fidout,'%s\n',files(cnt).name);
fidin=fopen(files(cnt).name);
fwrite(fidout,fread(fidin));
fprintf(fidout,'\n');
fclose(fidin);
end
fclose(fidout);
will merge the files and add the file names. What do you mean with a separate variable that shows the headers? If you want to store the headers in a variable, you can preallocate the headers before the loop:
headers=cell(size(files));
then save the first line of each file if there are letters:
fidin=fopen(files(cnt).name); %until here as in the upper code
first_line=fgets(fidin);
if any(isstrprop(first_line,'alpha'))
headers{cnt}=first_line;
end
fwrite(fidout,first_line);
fwrite(fidout,fread(fidin)); %continue with the upper code
댓글 수: 1
Michael Haderlein
2014년 8월 13일
Ok, maybe this time the code does what you want...
files=dir('test*.txt');
output='data.txt';
fidout=fopen(output,'w');
headers=cell(size(files));
numbers=cell(size(files));
for cnt=1:length(files)
fprintf(fidout,'%s\n',files(cnt).name);
fidin=fopen(files(cnt).name);
temp=fscanf(fidin,'%c');
if isstrprop(temp(1),'alpha')
headers{cnt}=temp(1:strfind(temp,sprintf('\n'))-2);
temp(1:strfind(temp,sprintf('\n')))='';
end
numbers{cnt}=str2num(temp);
fprintf(fidout,temp);
fprintf(fidout,'\n');
fclose(fidin);
end
fclose(fidout);
In case all files have the same number of columns, you can convert the numbers cell to an array:
numbers=cell2mat(numbers);
Please note that in this example I assume that the line break in the text files is \cr\lf (ascii codes 13 10). If your file has a different line break, you might need to change the -2 to -1 and change the line separator.
mkmat
2014년 8월 11일
댓글 수: 1
Michael Haderlein
2014년 8월 12일
Ok, your question is different from the first one. Do I understand correctly, in the data.txt you do not want to have the headers but only the numbers? And you want to get two variables, one with the headers and one with the data? "eliminate them from the files": Do you want to remove the headers from the input files?
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!