Processing txt multiple files in a folder and saving them using the original name but different format

3 views (last 30 days)
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

Accepted Answer

Rik
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
Amanuel Hailu Mamo
Amanuel Hailu Mamo on 22 Oct 2020
Thanks, what If I want to save it to a subfolder
Where do I add that function or ammend a function?
Does dlmwrite support that?
Rik
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.

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!