On a mac, how do I overwrite files in a folder in the working directory
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Walter Roberson
am 12 Dez. 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);
Antworten (1)
Walter Roberson
am 11 Dez. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Data Import and Analysis finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!