How to save the contents of an external file, located outside of MATLAB project path, in an internal MATLAB variable

3 ビュー (過去 30 日間)
Hugo
Hugo 2021 年 5 月 27 日
編集済み: Stephen23 2021 年 5 月 27 日
Hi, I would like to save the contents of an external file in the variable data. So far, I have this code, and it works:
file = "1.txt";
ffile = fopen(file,"rt");
temp = textscan(ffile,"%s","delimiter","\n");
data = temp{1};
fclose(ffile);
However, the file 1.txt must be in the active MATLAB path. I would like to change the path to
I tried to change the first line to: file = "C:\path1\path2\1.txt", but I get the following errors.
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in readres (line 6)
temp = textscan(ffile,"%s","delimiter","\n");
Does someone have any suggestion on how to get this to work?
I thank you in advance,
  3 件のコメント
Hugo
Hugo 2021 年 5 月 27 日
The thread was edited. Thank you for your suggestion.
Stephen23
Stephen23 2021 年 5 月 27 日
編集済み: Stephen23 2021 年 5 月 27 日
Get a more informative error message by obtaining the second output of fopen:
P = 'C:\path1\path2';
F = '1.txt';
[fid,msg] = fopen(fullfile(P,F),'rt');
assert(fid>=3,msg)
% your file importing code
fclose(fid)
But in any case, it looks like you should be using readlines:

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by