Processing txt multiple files in a folder and saving them using the original name but different format
3 views (last 30 days)
Show older comments
Hi guys,
I'd like to process all files in a folder and do some sorting and save it in a subfolder with the original name but differnet file format.
I tried using dlmwrite to save at the end of my code. But it overwrites each loop.
The txt file is a strain data with a size 1326 X 304
Here is the structure of files
files =
56×1 struct array with fields:
name
folder
date
bytes
isdir
datenum
Here is my code
% Convert raw data files into clean data with header
clc;clear; close('all')
files = dir(fullfile('*.txt'));
Pars.date = 1;
%% Loop
for i = 1:numel(files)
fid = fopen(files(i).name);
txt = textscan(fid,repmat('%f ',1,304),'delimiter','\n','HeaderLines',9);
rawdata = cell2mat(txt);
data = rawdata;
data(:,1:3) = round(data(:,1:3),6);
data =sortrows(data,1);
data = flipud(data);
X = data(:,4:end);
filename = files(i).name;
addpath('sorted_csv')
dlmwrite(filename.csv,X,'precision',16);
end
I'm not sure if I'm missing anything, Can anybody help? Let me know if you need additianal information to solve this
I also attached a sample txt file
2 Comments
Accepted Answer
Rik
on 22 Oct 2020
Something like this should work:
%replace this:
filename = files(i).name;
addpath('sorted_csv')
dlmwrite(filename.csv,X,'precision',16);
%with this:
[~,name,ext]=fileparts(files(i).name);
outfilename=fullfile(files(i).folder,[name '.csv']);
dlmwrite(outfilename,X,'precision',16);
2 Comments
Rik
on 22 Oct 2020
Did you have a look at the documentation for dlmwrite? Did you have a look at the content of the outfilename variable?
dlmwrite allows you to specify the full path, so if you change the path contained in outfilename you can specify a subfolder.
More Answers (0)
See Also
Categories
Find more on Text Files 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!