Using movefile to rename files
    13 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    ardeshir moeinian
 el 5 de Mzo. de 2020
  
    
    
    
    
    Editada: Image Analyst
      
      
 el 5 de Mzo. de 2020
            Hi everyone, 
I have a number of data files with .txt format which I want to rename. I use the following code to read the files: 
Foldername = uigetdir('\'); % Choose raw data folder
folder = [Foldername,'\'];
folder_parts=regexp(folder,'\','split')';
files = dir(fullfile([folder],'*.txt') ); % ('*.txt' for finding only .txt);
file = {files.name}';
And after this point I want to change some of the file names. for example  'Cell4_pH6,6_2.txt' to 'Cell5_pH6,6_2'
Textfiles={files.name}';
for i=1:length(Textfiles)
    newfile=strrep(Textfiles(i,:),'Cell5','Cell6');
    oldfilename=convertCharsToStrings(Textfiles(i,:));
    newfilename=convertCharsToStrings(newfile);
    movefile(oldfilename,newfilename);
end
When I use the above commands I get an error: 
Error using movefile
Cannot copy or move a file or directory onto itself.
How can I fix this?
Thank you!
0 comentarios
Respuesta aceptada
  Image Analyst
      
      
 el 5 de Mzo. de 2020
        
      Editada: Image Analyst
      
      
 el 5 de Mzo. de 2020
  
      You have a file where Cell5 does not occur in the name, so skip that one
Put this right after the for, as the first thing in the loop
if ~contains(Textfiles(i,:), 'Cell5', 'IgnoreCase', true)
    continue; % Skip this file.
end
Alternatively, or perhaps even better since it does not depend on any particular string leteral being in the name, you could do
if ~isequal(oldfilename, oldfilename)
    % Only rename if the filenames are different.
    movefile(oldfilename, newfilename);
end
0 comentarios
Más respuestas (0)
Ver también
Categorías
				Más información sobre File Operations en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!