Handle a .csv file and save folder path
9 次查看(过去 30 天)
显示 更早的评论
Hi I've got this simple matlab script :
clear all;
close all;
clc;
outFileName = [‘fileTest.csv'];
fid = fopen(outFileName, 'w');
fprintf(fid,'Colonna1, Colonna2, Colonna3, Colonna4\n');
mattiz = zeros(1000,4);
for i=1:1:1000
matrice(i,:) = [i i i i];
fid = fopen(outFileName, 'a');
fprintf(fid,'%d, ', matrice(i,1));
fprintf(fid,'%d, ', matrice(i,2));
fprintf(fid,'%d, ', matrice(i,3));
fprintf(fid,'%d,\n', matrice(i,4));
fclose(fid);
end
I would save my fileTest in the desktop, I'm running Matlab 2013b on a MacBook Pro, how should I write the path? With backslash or not? Thank you.
0 个评论
回答(2 个)
Geoff Hayes
2014-6-17
编辑:Geoff Hayes
2014-6-17
If you want to save the file to a particular directory (i.e. the desktop) then you could do something like the following
directory = '/Users/geoff/Desktop';
filename = 'fileTest.csv';
fileDest = fullfile(directory,filename);
fid = fopen(fileDest, 'w');
if fid>0
% do your work
for i=1:1:1000
% stuff
end
% close the file
fclose(fid);
end
One thing you may want to consider in your code is to remove the repetitive opening of the file on each iteration of the loop
fid = fopen(outFileName, 'a');
While this is "allowed", there is no corresponding fclose(fid) for each fopen so you have multiple file descriptors for the same file which may lead to difficulty trying to open that file in another application - you will have to close all file descriptors or shut down MATLAB in order to view that file.
Since you already have the file descriptor from when you opened the file, then just re-use that one and don't try to get another.
And all iterations have been completed, close the file with fclose(fid), like in the sample code of this answer.
Try the above and see what happens!
EDIT check out fileDest once this variable has been initialized and observe the effect of fullfile (it will add the slash for you).
0 个评论
Ken Atwell
2014-6-17
Since you are ultimately creating a CSV file, you do this much more directly using the table data type:
M = zeros(1000,4);
% Do math
T = array2table(M, 'VariableNames', {'Colonna1', 'Colonna2', 'Colonna3', 'Colonna4'});
writetable(T, '/Users/geoff/Desktop/output.csv')
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!