Convert txt files in csv/xlsx files
28 views (last 30 days)
Show older comments
Giggs B.
on 4 Aug 2022
Answered: Walter Roberson
on 4 Aug 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.
0 Comments
Accepted Answer
Walter Roberson
on 4 Aug 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.
0 Comments
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!