python解決方案:WindowsError: [Error 2],pythonwindowserror

來源:互聯網
上載者:User

python解決方案:WindowsError: [Error 2],pythonwindowserror

使用Python的rename()函數重新命名檔案時出現問題,提示 WindowsError: [Error 2] 錯誤,最初代碼如下:

def renameFile(filename):  filePre = "D:\\FileDemo\\Python\\pt.py"  os.rename(filePre, filename)  print os.listdir(filePre)if __name__ == '__main__':  fileNew = "D:\\FileDemo\\Python\\Test.py"  renameFile(fileNew)

後來經過反覆嘗試,問題解決~

  rename之前要先用chdir()函數進入到目標檔案所在的路徑,告訴python編譯器要重新命名的檔案在哪兒,然後才可以修改;

  Python不是可怕的終結者,她其實很幼小,自己找不到檔案,需要我們詳細又耐心的告訴她該去哪兒找~ 路徑通過 os.path.dirname()函數獲得:

import osfrom nt import chdirdef renameF(preName, newName):  chdir(os.path.dirname(preName))  os.rename(preName, newName)if __name__ == '__main__':  filePre = "D:\FileDemo\Python\PT.py"  fileNew = "D:\FileDemo\Python\Test.txt"  renameF(filePre, fileNew)

代碼非常簡潔,通過修改filePre,fileNew可以重新命名任意檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.