How can I iterate through all .txt files in a folder to process them with already written code?
16 views (last 30 days)
Show older comments
Alexandra
on 5 Jun 2023
Answered: Walter Roberson
on 5 Jun 2023
I have raw mass spectral data in .txt files with m/z in one column and intensity in another column. Right now, I'm importing them individually using the textread function. I know the textread function is not suggested for use anymore, and I want to speed up my processing. Is there functions that would allow me to run through all of my data in a folder, typically one day's worth of data, and process it that way? I know it would probably include a for loop, but I'm unsure how to write it.
0 Comments
Accepted Answer
Walter Roberson
on 5 Jun 2023
projectdir = 'location/of/text/files';
dinfo = dir(fullfile(projectdir, '*.txt'));
filenames = fullfile({dinfo.folder}, {dinfo.name});
numfiles = length(filenames);
for K = 1 : numfiles
thisfile = filenames{K};
thisdata = load(thisfile);
mz = thisdata(:,1); intensity = thisdata(:,2);
do something with mz and intensity
end
This assumes that the files are text files that have no headers (*) and are pure text in two columns separated by space or comma. load() of such a file will handle csv files for example.
If there are headers, then the easiest change is to switch from load() to readmatrix()
(*) Note: load() can handle headers in text file under the restricted situation that the header or comments have % as their first non-blank character on the line
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Import and Analysis 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!