How to convert csv data with decimal csv

1 次查看(过去 30 天)
Hello Matlab Experts,
I am converting my csv (english) version to erman version. However getting the converted csv with extra space raw. Can anyone help me?
Thank you
clear all
str = fileread('C:\Users\Cha\Desktop\TOUCH.csv');
str = strrep(str, ',', ';');
str = strrep(str, '.', ',');
f = fopen('TOUCH.csv', 'wt');
fprintf(f, '%s', str);
fclose(f);
  1 个评论
Ive J
Ive J 2020-12-18
Can you share your original file (TOUCH.csv) or a simulated one with the same structure?

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2020-12-18
Change
f = fopen('TOUCH.csv', 'wt');
to
f = fopen('TOUCH.csv', 'w');
When you do fileread(), the character vector that is read in will have inside it any carriage returns and linefeeds that are in the original text. When you fwrite() when 'wt' is active, every newline to be written will be converted to carriage return followed by newline. So what was originally CR LF in your file would get written out as CR CR LF .
If you had reason to want to force CR LF line ending, then use 'w', but
str = strrep(strrep(str, char(13), ''), char(10), char([13 10]))
This would remove all existing carriage returns and then change all newline to carriage return followed by newline.
Or alternately you could write the entire replacement series with no strrep, using
str = regexprep(str, {',', '\.', '(?<!\r)\n'}, {';', ',', '\r\n'})
This does all of the replacements, and only converts \n to \r\n if the \n was not proceeded by a \r already.
  8 个评论
Walter Roberson
Walter Roberson 2020-12-23
myfilename = dir('*.csv');
allfilenames = {myfilename.name};
%get rid of ones that are already _ge.csv
mask = ~cellfun(@isempty, regexp(allfilenames, '_ge\.csv$', 'once'));
allfilenames(mask) = [];
numfiles= length(allfilenames);
for k = 1:numfiles
oldname = allfilenames{K};
newname = regexprep(oldname, '\.csv', '_ge.csv');
mydata = fileread(oldname);
str = regexprep(mydata, {',','\.','(?<!\r)\n'}, {';',',','\r\n'});
f = fopen(newname, 'w');
fwrite(f, str);
fclose(f);
end
Mohammed Cha
Mohammed Cha 2020-12-23
Thank you very very much Sir. It works now.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Language Support 的更多信息

产品


版本

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by