On a mac, how do I overwrite files in a folder in the working directory
5 views (last 30 days)
Show older comments
I'm working on a mac. I have a folder in the working directory with six files. I am writing a script to read the files one at a time with a loop, change it and want to overwrite the original file with the reworked one. The script works fine until I try to send the file back to the working directory. I tried sending them to another folder, but that didn't work either. I think there must be a simple way to do this, but I obviously haven't thought of it. Help would be greatly appreciated.
1 Comment
Walter Roberson
on 12 Dec 2017
[From duplicate post]
Supplement: I forgot to add that the last thing I tried is:
str='megan/megan1.png'; %(1 of 6) saveas(gcf,str);
Answers (1)
Walter Roberson
on 11 Dec 2017
Best practice is to write to a different output file, renaming only after you are sure everything has worked.
For example,
%change line ending with theta = value to theta = newtheta
newtheta = 1.39184;
oldinput = 'theta\s*=.*$';
newoutput = sprintf('theta = %.5f', newtheta);
dinfo = dir('*.txt');
filenames = {dinfo.name};
for K = 1 : length(filenames)
thisfile = filenames{K};
S = fileread(thisfile);
newS = regexprep(S, oldinput, newoutput, 'dotexceptnewline');
newname = ['new_', thisfile];
[fid, msg] = fopen(newname, 'w');
if fid < 0
error('Could not open file "%s" because "%s"', newname, msg);
end
fwrite(fid, newS);
fclose(fid);
backup_name = ['old_', thisfile];
try
movefile(thisfile, backup_name);
catch ME
error('Failed renaming existing file "%s" to backup name "%s"', thisfile, backup_name);
end
try
movefile(newname, thisfile);
catch ME
error('Problem moving new file "%s" to existing name "%s", but file "%s" should have the saved contents of the old file', newname, thisfile, backup_name);
end
end
0 Comments
See Also
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!