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

5 ビュー (過去 30 日間)
qurat ul ain
qurat ul ain 2021 年 5 月 20 日
回答済み: Tejas 2025 年 7 月 7 日
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 Center および File ExchangeSoftware Development Tools についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by