MATLAB Answers

How to read CSV file and save the result to another CSV file

1 view (last 30 days)
Kong on 26 Mar 2020
Edited: Peng Li on 26 Mar 2020
I have several CSV files.
After processing each CSV file, I want to save each CSV file to other name using for loop.
The names of input file are different (bend1.csv, walk2.csv, jogging2.csv, ....)
clear all
close all
X = csvread('bend1.csv');
X = X(:,1:28);
data = X';
% After processing......
% I want to each Y matrix to CSV files
Y = Phi_NuMax * X';
csvwrite('/result/bend1.csv', Y);


Akira Agata
Akira Agata on 26 Mar 2020
You mean, you have many CSV files in one folder and want to save in another folder with the same file name after applying some processing?

Sign in to comment.

Accepted Answer

Peng Li
Peng Li on 26 Mar 2020
a simple structure:
outDir = yourDestination.
allCsvFiles = dir(fullfile(yourDirectory, '.*csv'));
for iA = 1:length(allCsvFiles)
curFile = allCsvFiles(iA).name;
yourTable = readtable(fullfile(yourDirectory, curFile));
% your process
writetable(fullfile(outDir, curFile), yourTable);


Show 3 older comments
Peng Li
Peng Li on 26 Mar 2020
Where did you save your csv file? using the directory to replace '/' when you call dir.
As you are saving the csv files with the same name, you don't want to replace your orignal files. So better designate a different directory for outDir.
Kong on 26 Mar 2020
I am sorry to bother you.
I changed outDir. When I tried to read each CSV file, what is Table?
yourTable is empty.
Peng Li
Peng Li on 26 Mar 2020
In the dir call, replace .*csv with *.csv.
Sorry it was my mistake that I had this typo in my example lol

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!