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

3 visualizaciones (últimos 30 días)
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

Respuestas (1)

Tejas
Tejas el 7 de Jul. de 2025
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:

Categorías

Más información sobre Software Development Tools en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by