Merging 4th column multiple text files into one file
显示 更早的评论
Hello, I want to do read column 4 of multiple text files (206) (all located in the same folder) and merge them into one file. My filenames consists of numbers for the first part, but the second part has a random name: 1802020100001_Grand-Maison-Dam.txt, 1802020100002_Vianden.txt, etc. The text files looks like this (all have the same number of rows (12) and columns (4)):
2015-01-31 6.05083 45.1453 2.17524
2015-02-28 6.05083 45.1453 0.267542
2015-03-31 6.05083 45.1453 8.07546
2015-04-30 6.05083 45.1453 30.029
2015-05-31 6.05083 45.1453 93.8143
2015-06-30 6.05083 45.1453 73.0604
2015-07-31 6.05083 45.1453 31.8136
2015-08-31 6.05083 45.1453 26.1006
2015-09-30 6.05083 45.1453 30.3608
2015-10-31 6.05083 45.1453 33.3809
2015-11-30 6.05083 45.1453 22.9509
2015-12-31 6.05083 45.1453 11.0744
I want to only read the fourth column of each textfile, transpose it to a row and add the rows below each other. In addition I want the first column to be the name of the file. So I want the output file to look like this:
Filename1 2.17524 0.267542 8.07546 30.029 93.8143 73.0604 31.8136 26.1006 30.3608 33.3809 22.9509 11.0744
Filename2 .. .. .. ..
I am new to matlab, I read some stuff about reading multiple text files and merging multiple files into one but I do not succeed to get the desired output and only have limited time to figure this out. Could someone help me with a code?
4 个评论
@Diede: "I read some stuff about reading multiple text files" - this makes it harder to post an answer. Now we know, that you have read something and repeating it would be a waste of time. But we do not know, what you have read already. Better post the code you have tried so far, such that we can improve it directly.
per isakson
2018-2-13
- Read all the txt-files in the folder ?
- Does the order of the rows in the result file matter ?
- tab as delimiter ?
Diede
2018-2-13
Diede
2018-2-13
回答(1 个)
Folder = 'C:\Your\Folder';
DirList = dir(fullfile(Folder, '*.txt'));
OutFID = fopen(fullfile(Folder, 'Output.txt', 'w');
if OutFID == -1, error('Cannot open file for writing.'); end
for iFile = 1:numel(DirList)
InFile = fullfile(Folder, DirList(iFile).name);
InFID = fopen(InFile, 'r');
if InFID == -1, error('Cannot open file for writing.'); end
DataC = textscan(InFID, '%*s%*s%*s%s');
fclose(InFID);
fprintf(OutFID, '%s', DirList(iFile).name);
fprintf(OutFID, ' %s', DataC{1}{:});
fprintf(OutFID, '\n');
end
fclose(OutFID);
You can solve such a problem by dividing it into parts:
- Process a sequence of files (See: https://www.mathworks.com/matlabcentral/answers/57446-faq-how-can-i-process-a-sequence-of-files )
- Import the wanted data from one file
- Export the wanted data to the output
Then solve one step after the other.
类别
在 帮助中心 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!