1. 程式人生 > 其它 >matlab 批量修改檔名常見錯誤

matlab 批量修改檔名常見錯誤

技術標籤:筆記matlabwindows

問題

我在使用matlab對刪格檔案進行計算時,發現由於命名問題,matlab讀取檔案順序並不是按照順序執行,例如,我的檔案命名是“1.tif’,‘2.tif’,……‘11.tif’,‘12,tif’。
那麼,matlab批量讀取的順序便是’1.tif’,‘10.tif’,‘11.tif’,‘12.tif’,‘2.tif’……‘9.tif‘。
為了解決這個問題,我需要將長度較小的檔案前面加一個’0‘,這樣,讀取順序會變為:’01.tif’,‘02.tif’……'12.tif’。
批量修改檔名的操作有很多種,在matlab中,常見的方法有:調動系統命令批量修改與使用matlab函式的copyfile 與movefile。

後者方法程式碼示例如下:

PDF files in the current folder
files = dir('*.pdf');

% Loop through each
for id = 1:length(files)
    % Get the file name (minus the extension)
    [~, f] = fileparts(files(id).name);

      % Convert to number
      num = str2double(f);
      if ~isnan(num)
          % If numeric, rename
          movefile
(files(id).name, sprintf('%03d.pdf', num)); end end

使用後者的好處是:限制少、語法更簡單好寫,功能更多(可以移動檔案或資料夾)
而且movefile是matlab函式,不會受到系統影響,而如果你使用system命令,在程式移植到其他系統中執行時如果系統命令的用法不同也會執行失敗
所以不管從相容性,還是簡潔,功能更強各個方面來說,movefile都是更好的選擇。
然而,movefile需要重新選擇資料夾或者在同一資料夾中,這會造成檔案冗餘情況,因此,若要直接對檔名進行修改,需要調動系統命令。

在搜尋matlab檔案重新命名時,你很容易搜到這樣的命令:

command = [‘rename’ 32 oldname 32 newname];
status = dos(command);
if status == 0
disp([oldname, ’ 已被重新命名為 ‘, newname])
else
disp([oldname, ’ 重新命名失敗!’])
break;
end
這個命令是針對預設路徑下matlab檔名批量修改,而在實際使用中,我們需要使用絕對路徑。並且,檔案路徑中若帶有空格,則需改為:
command = [‘RENAME’ 32 ,’"’,oldname,’"’,32 newname];
然而,你會發現在實際使用中,命名沒有空格,仍會出現語法出錯和命名失敗的問題,這就我下面要強調的一點:
開啟cmd,輸入rename:
在這裡插入圖片描述
注意上面的格式,path只有在filename1前才有,也就是說,如果你要輸入絕對路徑,只要在oldname輸入即可,newname是不可以包含路徑的!!

下面給出我的程式碼:

year=2005:2014;
path2='D:\data\AI_proj\result\resample\';
for i=1:length(year)
    filepath{i}=strcat(path2,num2str(year(i)),'\');
end
for k=1:length(year)
    e=dir([filepath{k},'*.tif']);
    for i=1:size(e,1)
        oldname=[filepath{k},e(i).name];
        if length(e(i).name)==13;
        newname=['0',e(i).name];%newname 不能帶路徑!
        status = system(['rename ',oldname,' ', newname]);
        end
    end
end

以上,親測可行,希望幫到各位,