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!

