Convert txt files in csv/xlsx files

18 ビュー (過去 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 Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by