Convert txt files in csv/xlsx files

조회 수: 16 (최근 30일)
Giggs B.
Giggs B. 2022년 8월 4일
답변: Walter Roberson 2022년 8월 4일
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.

채택된 답변

Walter Roberson
Walter Roberson 2022년 8월 4일
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개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by