How to convert csv file to .dat file?

I want to read a csv file and save it as .dat file without the commas. How can I do so?

 Respuesta aceptada

Voss
Voss el 18 de Mzo. de 2022
Editada: Voss el 18 de Mzo. de 2022
% read the csv file:
data = readmatrix('data.csv')
data = 4×3
1 2 3 4 5 6 7 8 9 10 11 12
% write the data to .dat file using
% space as the delimiter (no commas):
writematrix(data,'data.dat','Delimiter',' ');
% check that the .dat file looks right:
fid = fopen('data.dat');
dat_data = fread(fid,'*char').';
fclose(fid);
disp(dat_data); % looks good
1 2 3 4 5 6 7 8 9 10 11 12
I assumed the .csv file contains just numbers. If that's not the case, then you'd have to use functions other than readmatrix() and writematrix().

6 comentarios

Hossam Amin
Hossam Amin el 19 de Mzo. de 2022
Thank you for the answer.
If I wanted to unify this code, to make it work on any csv file I have, by calling it as a function, what tweaks do I need to do? Instead of changing the filename on every file I want to convert.
Voss
Voss el 19 de Mzo. de 2022
Editada: Voss el 19 de Mzo. de 2022
This will create a .dat file with the same name and location as the .csv file given:
% calling the function, with the .csv file name as the input:
convert_csv_to_dat('data.csv')
% function definition:
function convert_csv_to_dat(csv_file)
% assume the name given is a name with .csv extension,
% and replace the 'csv' extension with 'dat' for the
% output file name (dat_file):
dat_file = csv_file;
dat_file(end-2:end) = 'dat';
% read the csv file:
data = readmatrix(csv_file);
% write the data to .dat file using
% space as the delimiter (no commas):
writematrix(data,dat_file,'Delimiter',' ');
end
Hossam Amin
Hossam Amin el 19 de Mzo. de 2022
Thank you
Voss
Voss el 19 de Mzo. de 2022
You're welcome!
Mateusz
Mateusz el 24 de Mzo. de 2023
Hi! How should I edit your script in order to modify multiple files file_00XXX.csv to dat files?
Thank you in advance!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Productos

Versión

R2021a

Preguntada:

el 18 de Mzo. de 2022

Comentada:

el 25 de Mzo. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by