write files in.csv format in separate loacation

조회 수: 3 (최근 30일)
Daphne Mariaravi
Daphne Mariaravi 2017년 6월 20일
댓글: Eric 2017년 6월 21일
Using xlsread command I read a large number of .csv files in a loop. I am using the following code to read rawdata and save the output in .csv format(should not ovewrite the existing file)
files=dir('new');
files=files(~[files.isdir]);
n=length(files);
for i=1:n
thisfile=xlsread(fullfile(files(i).folder,files(i).name));
[~,~,rawdata]= xlsread(fullfile(files(i).folder, files(i).name));
A=csvread(rawdata);
A=rawdata(2:end,4);
B=cumsum(cellfun(@double,A));
xlswrite('thisfile.csv', [{'cumulative'}; num2cell(B)], 1, 'D1');
end
However the code just saves the output of the last file in the folder. How do I get the results of n files saved as n different.csv files?

채택된 답변

Eric
Eric 2017년 6월 20일
You're saving everything to 'thisfile.csv'. You need to change the filename with each iteration of the for loop. Try something like
files=dir('new');
files=files(~[files.isdir]);
n=length(files);
for i=1:n
thisfile=xlsread(fullfile(files(i).folder,files(i).name));
[~,~,rawdata]= xlsread(fullfile(files(i).folder, files(i).name));
A=csvread(rawdata);
A=rawdata(2:end,4);
B=cumsum(cellfun(@double,A));
[~, fname] = fileparts(files(i).name);
new_filename = fullfile(files(i).folder, [fname '.csv']);
xlswrite(new_filename, [{'cumulative'}; num2cell(B)], 1, 'D1');
end
This will write a CSV file of the same root filename in the same directory as the original file.
  댓글 수: 2
Daphne Mariaravi
Daphne Mariaravi 2017년 6월 21일
@Eric it works well but it overwrites my original files. Could that be sorted? Also this line works for writing one set of values(cumulative sum) in a dedicated column.
xlswrite(new_filename, [{'cumulative'}; num2cell(B)], 1, 'D1');
What if I need to write more parameters like median, mean etc in separate columns?
Eric
Eric 2017년 6월 21일
In regards to overwriting the original files, I was thinking your original files have an extension of XLS or XLSX. I now gather that they are also CSV files. How about something like:
filename = fullfile(files(i).folder, [fname '_new.csv']);
Have you thought about using Matlab tables for this problem? At least as of a few years ago, xlsread and xlswrite both opened and closed Excel every time they are called, causing significant overhead. I went to the trouble of creating my own class for interfacing to Excel to avoid this.
I wonder if you could use readtable instead of xlsread and writetable instead of xlswrite. You could then add new parameters like median, mean, and so forth as new parameters in the table prior to calling writetable(). That might simplify your code, make it faster, and allow new data sets to easily be written.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by