MATLAB Answers

0

How to process .txt files in a folder to be read by readtable?

Asked by Kamila Turczewski on 11 Jul 2019
Latest activity Commented on by Kamila Turczewski on 13 Jul 2019
I have a folder with a large amount of the same type of file in them with data I want to be processed using the same code. Is there a way I can loop through the folder to read each .txt file to have it be read by using readtable()? I would prefer to use readtable() compared to other import methods. The folder of data is already organized how I'd like it.
data = readtable('01048000D.txt', 'Format', '%q %f %f %f %f %f', 'Delimiter', 'unspecified', 'Headerlines' , 0, 'ReadVariableNames', false)
I just need a way for all of the files to be read in this one folder. I would like to just have the loop change what the file name would be, but I don't know how to do this.

  0 Comments

Sign in to comment.

Tags

1 Answer

Answer by KSSV
on 11 Jul 2019

txtfiles = dir('*.txt') ;
N = length(txtfiles) ;
data = cell(N,1) ;
for i = 1:N
data{i} = readtable(txtfiles(i).name, 'Format', '%q %f %f %f %f %f', 'Delimiter', 'unspecified', 'Headerlines' , 0, 'ReadVariableNames', false) ;
end

  1 Comment

What do I do if there is another file in a different folder with the same filename, but it has different data in it?
I have two folders DailyData and DailyBaseline Data. Is there a way where in the loop I can specify which folder the data is coming from? I keep getting an error when trying to run it during the loop and I think its due to MatLab using the wrong file in the other folder.
I found this on readtable() :
File in a folder
If the file is not in the current folder or in a folder on the MATLAB path, then specify the full or relative path name in filename.
Example: 'C:\myFolder\myFile.xlsx'
Example: 'dataDir\myFile.txt'
Would I have to do this? and if so how do I do it because it isn't working when I do
C:\DailyData\01048000.txt
Screen Shot 2019-07-13 at 11.18.39 AM.png

Sign in to comment.