MATLAB Answers

Extracting a file path from a .txt file

73 views (last 30 days)
Camille Couzi
Camille Couzi on 12 Jun 2018
Commented: Camille Couzi on 16 Jan 2020
Hi, I want to build a script that is able to retrieve information from a text file that has a specific format. I have simplified a lot what's below so everyone can understand my problem, which is pretty basic. This is a sample of such file, stored as "mytestfile.txt':
% Your inputs start after the line.
% ---------------------------------------------
% Raw data full path folder:
InputFolder C:\Users\Cami\Documents\Processing Tool\Test Folder - Trial 1
% Distance from seabed to transducer head (in meters)
instrument_nominal_height 0.9
So I have started to write a code that reads this text file:
for p=1:length(A)
if test~=0
[a,result.InputFolder]=strread(char(A(p)),'%s %s');
clear a
if test~=0
[a,result.instrument_nominal_height]=strread(char(A(p)),'%s %f');
clear a
result.instrument_nominal_height works fine, it picks up 0.9 as a float. But I am having trouble with result.InputFolder because the string has spaces and a "-". I get this:
result =
struct with fields:
InputFolder: {5×1 cell}
instrument_nominal_height: 0.900000000000000
>> result.InputFolder
ans =
3×1 cell array
Do you have a better method to do this? I can't change the paths of the folders where my text files will be stored, as this is part of my company's drive.
Thanks doe your help! Cheers, Cami.
  1 Comment
Stephen Cobeldick
Stephen Cobeldick on 12 Jun 2018
@Camille Couzi: please upload a sample data file by clicking the paperclip button.

Sign in to comment.

Answers (2)

Alfonso on 12 Jun 2018
Edited: Alfonso on 12 Jun 2018
Attending to the title of your question, in order to extract the full path filename of a file:
% Select the file you want to open %
defaultFileName = fullfile(cd, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select file');
if baseFileName == 0
fullFileName = fullfile(folder, baseFileName); % Full path filename
if ~exist(fullFileName, 'file')
fullFileName = baseFileName;
if ~exist(fullFileName, 'file')
fullFileName is the full path of the selected file.
Camille Couzi
Camille Couzi on 16 Jan 2020
Sorry kc,
This was quite some time ago, in a different job and I don't remember what solution I used. Good luck!

Sign in to comment.

Paolo on 12 Jun 2018
Edited: Paolo on 12 Jun 2018
You can use regexp to match the path in your .txt file.
corr = fileread('mytestfile.txt');
path =
{'C:\Users\Cami\Documents\Processing Tool\Test Folder - Trial 1'}
Paolo on 13 Jun 2018
You are welcome, if it solved the problem you can accept the answer.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!