MATLAB: How to write from a python file to another python script, modify the new python script and save it into a new path.

MATLAB

replaceLine =2;
fid = fopen('Downloads\mat.py', 'r+');
X = fread(fid);
fclose(fid);
for k=1:(replaceLine-1);
fgetl(X);
end
fseek(X, 1, 'bof');
fprintf(X,'%s',mat_file);
py_File= sprintf('r%d_r%dr.py',pressure_grad,pressure_max); %filename of py file
path1=['F:\excel\' py_file];
fwrite(path1,X);
I am getting an error in fread function and fgetl function.

Best Answer

The reason for the error in ‘fgetl’ was because you were trying to pass the content 'X' read from the file using 'fread', as input in 'fgetl'.
'fgetl' takes only the file descriptor as input. You can go through these links for more information on fread and fgetl
Additionally, you can go through the below code for reading from one file and writing to another file
fid1 = fopen(readFile, 'r');
line = fgetl(fid1);
lines = cell(0,1);
while(ischar(line))
lines{end+1,1} = line;
line = fgetl(fid1);
end
fclose(fid1);
fid2 = fopen(writeFile, 'a');
for i=1:length(lines)
fprintf(fid2,'%s\n',lines{i});
end
fclose(fid2);
where 'readFile' and 'writeFile' are the variables storing the locations of the files you are trying to read from and write to respectively