MATLAB Answers

Aj
0

Saving textfiles in a other folder

Asked by Aj
on 1 Oct 2019
Latest activity Commented on by Aj
on 1 Oct 2019
Hello there,
I try to open a text file in a other folder, replace "," with "." and to close and save.
It works, but the new text is saved in the folder of my matlabscript. But I want, that it saved there, where it tooks the textfile to manipulate it, just overwrite the old one.
Maybe someone can help me. Thanks!
addpath('E:\Data\Test\X')
testfiledir = 'E:\Data\Test\X';
matfiles = dir(fullfile(testfiledir, '*.txt'));
% A=dir ('*.txt')
B=matfiles(1).name;
FileName=B;
Data = fileread(FileName);
Data = strrep(Data, ',', '.');
FID = fopen(FileName, 'w');
fwrite(FID, Data, 'char');
fclose(FID);
% type FileName; hier nicht benötigt
M= readmatrix(FileName);

  0 Comments

Sign in to comment.

Tags

1 Answer

Answer by Guillaume
on 1 Oct 2019
 Accepted Answer

It's never a good idea to modify the matlab path (with addpath or others) just to read or write data files.
The simplest way to make sure that a file is read or written in the correct folder is to simply specify the folder as part of the name when you read/write. It's easy to do: use fullfile. You've done exactly that for your dir call. Why didn't you do the same for your fopen calls.
On a completely unrelated subject, matfiles is a fairly good variable name (dircontent may be better), FileName is also a good variable name, it's easy to understand what the variables contains. B is a horrendous variable name. It's also completely pointless in your code, it's unclear why you couldn't just have done
FileName = matfiles(i).name;
and not bother with the B or even better, keep using matfiles(i).name everywhere.
So, in the end:
testfiledir = 'E:\Data\Test\X'; %assuming it's both the input and output directory
matfiles = dir(fullfile(testfiledir, '*.txt'));
for i = 1:numel(matfiles)
Data = fileread(fullfile(testfiledir, matfiles(i).name));
Data = strrep(Data, ',', '.');
FID = fopen(fullfile(testfiledir, matfiles(i).name), 'w');
fwrite(FID, Data); %no need for char. not sure char is even valid
fclose(FID);
While you could also use readmatrix or readtable as suggested, it may change other formatting of the file and will be slower than the above due to the parsing it does.

  1 Comment

Aj
on 1 Oct 2019
Hello,
Your answer help me so much! Thanks for the advices to write and keep codes short and now everything works like I want.
Thank you very much!!!

Sign in to comment.