os.renames(old, new)
old -- 這是要重新命名的檔案或目錄的實際名稱
new -- 這是在檔案或目錄的新名稱。它甚至可以包括一個檔案到一個目錄,或目錄的整個樹,即不存在。
# !/usr/bin/python3 import os, sys os.chdir("d:\\tmp") print ("Current directory is: %s" %os.getcwd()) # listing directories print ("The dir is: %s"%os.listdir(os.getcwd())) # renaming file "aa1.txt" os.renames("foo.txt","newdir/foonew.txt") print ("Successfully renamed.") # listing directories after renaming and moving "foo.txt" print ("The dir is: %s" %os.listdir(os.getcwd())) os.chdir("newdir") print ("The dir is: %s" %os.listdir(os.getcwd()))
Current directory is: d:\tmp The dir is: ['Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 'java.ppt', 'python2'] Successfully renamed. The dir is: ['Applicationdocs.docx', 'book.zip', 'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 'java.ppt', 'newdir', 'python2']
The dir is: ['foonew.txt']