multiple csv files merging in one file, with each file name as category in merged file

3 次查看(过去 30 天)
i have 100 different csv files of different categories of data.i want to merge that data in one file and then add name of the each file as a category in separate column in same file(the name of file is should be added to the dta of that file only)
the data of all csv files shoud be merged and categorized by the respective file name in one file

回答(1 个)

Tejas
Tejas 2025-7-7
Hello Qurat,
I am assuming that all the CSV files have the same number of columns and share the same column names.
To merge these CSV files into a single file and add an extra column to represent the data category, follow these steps:
  • Read the contents of each CSV file into a cell array, and extract the file name to use as the category label.
files = dir('*.csv');
allTables = cell(length(files),1);
for i = 1:length(files)
tbl = readtable(files(i).name);
[~, fileName, ~] = fileparts(files(i).name);
tbl.Category = repmat({fileName}, height(tbl), 1);
allTables{i} = tbl;
end
  • Merge the data from all the CSV files into one comprehensive file.
mergedTable = vertcat(allTables{:});
writetable(mergedTable, 'merged_data.csv');
For better understanding of the solution, refer to the following documentations:

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by