필터 지우기
필터 지우기

Searching for a file when the filename is always changing

조회 수: 2 (최근 30일)
Tat Onn Huen
Tat Onn Huen 2021년 9월 1일
댓글: Tat Onn Huen 2021년 9월 2일
Hi I am trying to readtable a dat file but the dat filename changes for different situations. Is it possible to readtable the dat file just based on the first few letters of the file?
sample = input('Sample? ', 's');
directory = 'C:\Users\tathuen\Desktop\Data\'
filename = append(directory, sample)
% Count number of location in file
dircontent = dir(filename);
numfolders = sum([dircontent.isdir]) - 2
% For loop to open all the data
for i = 1:numfolders
% Opening each dat files
T1 = readtable(append('C:\Users\tathuen\Desktop\Data\', sample, '\location', num2str(i), '-----\test-----\test1.dat'));
For example, the filename will always be 'location 1 (random letters) \ test (random letters)'. Is it possible to locate the file just based on 'location 1' and 'test'?
Thanks in advance! :)
  댓글 수: 2
Ive J
Ive J 2021년 9월 1일
if your file name always has a certain pattern, yes you can use regexp or pattern to find your file. Example:
filenames = ["this.file.dat", "that.file.dat", "bla.dat", "targetXXXX.dat"]; % different .dat files in the directory
% I'm looking for a dat file starting with "target"
myfile = filenames(startsWith(filenames, "target"))
myfile = "targetXXXX.dat"
Tat Onn Huen
Tat Onn Huen 2021년 9월 2일
i couldnt get this to work as the filenames were random so i couldnt create a filenames = [ ]. thanks for helping!

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2021년 9월 1일
"the filename will always be 'location 1 (random letters) \ test (random letters)'."
rootdir='C:\Users\tathuen\Desktop\Data\';
fSearch=fullfile(rootdir,'location*','test.*'); % build matching wildcard expression
d=dir(fSearch); % and look for match
for i=1:numel(d)
T1 = readtable(fullfile(d(i).folder.d(i).name);
...
Fix up the sample pattern to match the actual pattern; I didn't try to parse the sample code extremely carefully...

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by