Filter löschen
Filter löschen

How to convert csv data with decimal csv

2 Ansichten (letzte 30 Tage)
Mohammed Cha
Mohammed Cha am 18 Dez. 2020
Kommentiert: Mohammed Cha am 23 Dez. 2020
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 Kommentar
Ive J
Ive J am 18 Dez. 2020
Can you share your original file (TOUCH.csv) or a simulated one with the same structure?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 18 Dez. 2020
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 Kommentare
Walter Roberson
Walter Roberson am 23 Dez. 2020
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 am 23 Dez. 2020
Thank you very very much Sir. It works now.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by