필터 지우기
필터 지우기

Saving textfiles in a other folder

조회 수: 3 (최근 30일)
Aj
Aj 2019년 10월 1일
댓글: Aj 2019년 10월 1일
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);

채택된 답변

Guillaume
Guillaume 2019년 10월 1일
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
Aj
Aj 2019년 10월 1일
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!!!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by