On a mac, how do I overwrite files in a folder in the working directory
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2017-12-12
[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);
回答(1 个)
Walter Roberson
2017-12-11
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!