Python os.renames()方法

Python的renames()方法是遞歸目錄或檔重命名功能。它與os.rename()執行相同的功能,但它也將檔或目錄的整個樹移動到不存在的目錄。

語法

以下是renames()方法的語法 -

os.renames(old, new)

參數

  • old - 這是要重命名的檔或目錄的實際名稱。
  • new - 這是檔或目錄的新名稱。甚至可以將檔包含到不存在的目錄或目錄的整個樹中。

返回值

  • 此方法不返回任何值。

示例

以下示例顯示了renames()方法的用法。

# !/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'
]

foo.txt在這裏不可見,因為它被移動到newdir並重命名為foonew.txt。 目錄newdir及其內容如下所示:

The dir is: ['foonew.txt']

上一篇: Python os模組方法 下一篇: Python異常處理