Convert txt files in csv/xlsx files

28 visualizaciones (últimos 30 días)
Giggs B.
Giggs B. el 4 de Ag. de 2022
Respondida: Walter Roberson el 4 de Ag. de 2022
Hello,
I have a couple hundreds of txt files, where a number is written in each row. I want to convert all these hundreds of txt files into csv/xlsx files having the same name as the txt file. For ex: I have txt files as 1.txt, 2.txt, 3.txt......so on. I want to convert these text files into csv/xlsx files as 1.csv, 2.csv, 3.csv....so on.
Can someone help me with a code snippet or a link to a post showing to automate this function in MATLAB? Thanks.

Respuesta aceptada

Walter Roberson
Walter Roberson el 4 de Ag. de 2022
dinfo = dir('*.txt');
filenames = {dinfo.name};
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
[~, basename, ~] = fileparts(thisfile);
newname = basename + ".xlsx";
data = readmatrix(thisfile);
writematrix(data, newname);
end
This code assumes that you do not have any header in the file -- if you have a variable name for each column then switch to readtable() and writetable()
This code assumes that all of the columns are the same type -- if not, then switch to readtable() and writetable(), possibly with 'writevariablenames', false if there should not be a header line.
This code assumes that the .txt file format is something that readmatrix() can guess at.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by