Read all .csv file in Folder , rearrange and write in one .csv file
1 view (last 30 days)
Show older comments
I have more than 150 .csv file in one folder all the .csv files are having same number of rows and column "10 rows and 5 columns". as shown below
File 1
P1C1.csv %(File 1)
1 11 21 31 41
2 12 22 32 42
3 13 23 33 43
4 14 24 34 44
5 15 25 35 45
6 16 26 36 46
7 17 27 37 47
8 18 28 38 48
9 19 29 39 49
10 20 30 40 50
File 2
P2C2.csv %(File 2)
51 61 71 81 91
52 62 72 82 92
53 63 73 83 93
54 64 74 84 94
55 65 75 85 95
56 66 76 86 96
57 67 77 87 97
58 68 78 88 98
59 69 79 89 99
60 70 80 90 100
like this above file 150 files are there in single folder.
I need to read all .csv file. Form each csv file i need to read first "8 rows and 5 column" and write it in one single sheet for all 150 files in order (File1, File 2,...,File 150). example is shown below.
Write1.csv
1 11 21 31 41 %(from File 1)
2 12 22 32 42
3 13 23 33 43
4 14 24 34 44
5 15 25 35 45
6 16 26 36 46
7 17 27 37 47
8 18 28 38 48
51 61 71 81 91 %(from File 2)
52 62 72 82 92
53 63 73 83 93
54 64 74 84 94
55 65 75 85 95
56 66 76 86 96
57 67 77 87 97
58 68 78 88 98
... %(from File 3)...
like this it go for 150 files. And remaining row number 9th and 10th for 5 column of each file is written in another single sheet same as like above example is showen below.
write2.csv
9 19 29 39 49 %(from File 1)
10 20 30 40 50
59 69 79 89 99 %(from File 2)
60 70 80 90 100
... %(from File 3...upto File 150)
Please Help me to solve. (THANK YOU)
2 Comments
Walter Roberson
on 23 May 2021
Does the order of the files matter? If so then what part of the file name can be used to determine the order?
Answers (1)
Stephen23
on 24 May 2021
Edited: Stephen23
on 24 May 2021
P = 'absolute or relative path to where the files are saved';
N = 150;
C1 = cell(1,N);
C2 = cell(1,N);
for k = 1:N
F = sprintf('P%dC%d.csv',k);
M = readmatrix(fullfile(P,F));
C1{k} = M(1:8,:);
C2{k} = M(9:10,:);
end
M1 = vertcat([C1{:}]);
writematrix(M1,fullfile(P,'write1.csv'))
M2 = vertcat([C2{:}]);
writematrix(M2,fullfile(P,'write2.csv'))
1 Comment
Walter Roberson
on 24 May 2021
F = sprintf('P%dC%d.csv',k);
You need two numeric parameters to format two %d properly.
See Also
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!