Clear Filters
Clear Filters

Not recognizing any text files in folder using dir(fullfile)

27 views (last 30 days)
I am trying to plot data from multiple text csv files in a folder. This is the first part of my code:
folder_path = 'C:users\power\downloads\star capillary files\'; % Replace with your folder path
% List all TXT files in the folder
txt_files = dir(fullfile(folder_path, '*.txt'));
for file_idx = 1:length(txt_files)
filename = fullfile(folder_path, txt_files(file_idx).name);
% Load the TXT file
data = readtable(filename, 'Delimiter', ',');
MATLAB is not recognizing that there are text files in my folder, though there are. I wrote a similar code to make calculations from a single txt file in that folder and it works. Does anyone know why it might not be recognizing txt files with this code? I added the folder to path in the MATLAB software by right clicking. Any help would be extremely appreciated!
  1 Comment
Stephen23
Stephen23 on 9 Jul 2024 at 20:42
"Does anyone know why it might not be recognizing txt files with this code?"
Compare:
'C:users\power\downloads\star capillary files\' % your path
'C:\users\power\downloads\star capillary files\' % valid Windows path

Sign in to comment.

Answers (2)

Voss
Voss on 9 Jul 2024 at 19:33

Try

folder_path = 'C:\users\power\downloads\star capillary files\';

instead of

folder_path = 'C:users\power\downloads\star capillary files\';

Image Analyst
Image Analyst on 9 Jul 2024 at 20:50
Edited: Image Analyst on 9 Jul 2024 at 20:51
You're missing the forward slash after the drive letter and colon. Put that in. Also, your code is not very robust. You could increase the robustness by using isfolder, like
folder_path = 'C:\users\power\downloads\star capillary files\';
if ~isfolder(folder_path)
% Folder does not exist. Alert user:
errorMessage = sprintf('Error: this folder does not exist:\n"%s"\nPlease select an existing folder in the next window.', folder_path)
uiwait(errordlg(errorMessage));
% Ask user to pick a valid folder.
folder_path = uigetdir();
if folder_path == 0
% user clicked Cancel button.
return;
end
% If we get to here, then folder_path is valid.
end
Then do your call to dir.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!