Python os.renames() 方法



Python OS 模組的renames()方法是一個遞迴的目錄或檔案重新命名函式。它與 os.rename()的功能相同,但它還會建立中間目錄(如果不存在)以完成新的檔案路徑。

語法

以下是 Python os.renames() 方法的語法:

os.renames(old, new)

引數

Python os.renames() 方法的引數如下所示:

  • old − 這是要重新命名的檔案或目錄的現有名稱。

  • new − 這是檔案或目錄的新名稱。它甚至可以包括將檔案移動到不存在的目錄或整個目錄樹中。

返回值

Python os.renames() 方法不返回值。

示例

以下示例演示了 renames() 方法的使用。這裡,我們將“aa1.txt”檔案重新命名為“aanew.txt”並將其移動到名為“newdir”的新目錄中。

import os, sys

print ("Current directory is: %s" %os.getcwd())

# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))

# renaming file "aa1.txt"
os.renames("aa1.txt","newdir/aanew.txt")

print ("Successfully renamed")

# listing directories after renaming and moving "aa1.txt"
print ("The dir is: %s" %os.listdir(os.getcwd()))

當我們執行上述程式時,它會產生以下結果:

Current directory is: /tmp
The dir is:
 [  'a1.txt','resume.doc','a3.py','aa1.txt','Administrator','amrood.admin' ]
Successfully renamed.
The dir is:
 [  'a1.txt','resume.doc','a3.py','Administrator','amrood.admin' ]

這裡看不到aa1.txt檔案,因為它已被移動到newdir並重命名為aanew.txt。“newdir”目錄及其內容如下所示:

[ 'aanew.txt' ]
python_files_io.htm
廣告