MATLAB: How to delimit (and replace) multiple CSV files in a loop

comma delimitcsvcsvreaddelimitexcelfor loopMATLABxlsreadxlswrite

I have several CSV files that contain data separated by commas (x, y, z) in column A. The headers are strings with parentheses ("XXXXXXXXXX (XX)", "YYYYYYYYYY (YYY)", "ZZZZZZZZZ"), while the data (x, y, z) are numerical values. Usually, I would highlight the A column and delimit the columns in Excel in order to separate my data into three separate columns in order to analyze. However, I have a lot of these files now, and I was wondering if I could write a for loop to read these files, delimit, replace the text in the original file in the correct number of columns, and save the new file again.
I tried csvread, but it's having trouble reading the commas. A sample CSV file is in the attachments. Thanks for any help in advance.

Best Answer

dinfo = dir('*.csv');
filenames = {dinfo.name};
for K = 1 : length(filenames)
thisfile = filenames{K};
[~, basename, ~] = fileparts(thisfile);
newfile = [basename '.txt'];
S = fileread(thisfile);
S(S=='"') = ''; %delete all double-quotes
fid = fopen(newfile, 'w');
fwrite(fid, S);
fclose(fid);
end
This writes to a different file name to avoid processing the same file more than once.
If you really insisted you could write to the same file again. You do run the risk of repeatedly processing the same file if you run the same code again, but in this special case it should be harmless since the code does not actually assume that there are any double-quotes in the file. If you needed the column header to have "" around each of the parts then you would need more work for the case of processing an already-processed file, but it would not be too bad.
Related Question