MATLAB 批量檔案重新命名(詳細解釋)

來源:互聯網
上載者:User

這段時間在用 matlab 做手寫數字識別,處理樣本的時候需要對樣本檔案進行重新命名,可是有好多,總不能一個一個重新命名吧,於是上網百度了好多,不過大多都一樣,但是沒有解釋,只有乾巴巴的程式,弄了好一會才弄清楚(我太菜了……),於是寫下了以備後用。 更新

這裡我會列出對本文的更新。 2017 年 3 月 21 日:最佳化排版,去除多餘和易誤導人的語句。 2017 年 3 月 25 日:最佳化代碼,增加重新命名成功失敗提示,增加程式的一點說明。 問題

假設我有 0.bmp, 1.bmp, 2.bmp, ……,99.bmp 等 100 個 bmp 影像檔,出於某種需要我要在名字前加上一個 RH_ 字串。 代碼

files = dir('*.bmp');len=length(files);for i=1:len    oldname=files(i).name;    newname=strcat('RH_', oldname);    command = ['rename' 32 oldname 32 newname];    status = dos(command);    if status == 0        disp([oldname, ' 已被重新命名為 ', newname])    else        disp([oldname, ' 重新命名失敗!'])    endend

解釋一下程式: 用 dir 函數獲得工作目錄下所有 bmp 檔案資訊,返回的 file 是一個 結構體,裡麵包含了檔案名稱、修改時間等資訊,我們用的就是第一個網域名稱字 name 獲得 bmp 檔案的個數 len 每一次迴圈用 strcat 函數將 RH_ 與原檔案名稱 oldname 串連起來,然後使用 dos 叫用作業系統命令替換掉原檔案名稱

關於這個 dos 函數的用法,這裡引用下 dos 函數的協助

status = dos(command) executes the specified MS-DOS® command for Windows® platforms, and waits for the command to finish execution before returning the exit status to the status variable.

這個函數實際上就是調用執行作業系統命令,比如這裡的 rename 命令,32 是 ASCII 碼,表示空格。

rename oldname newname
一點說明

我上面的程式是將程式和我要重新命名的圖片放在了 MATLAB 的 當前路徑 下,所有可以不用寫絕對路徑,但是如果你想要指定圖片檔案的絕對路徑,那麼就要 保證你的路徑中不包含空格,不然會報錯:The syntax of the command is incorrect. 同樣引用下 這篇文章 的說法:

Rename the file “computer hope.txt” to “example file.txt”. Whenever dealing with a file or directory with a space, it must be surrounded with quotes. Otherwise, you’ll get the The syntax of the command is incorrect error. END

好了,又是十二點了,就到這吧,歡迎交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.