Python os.renames()方法

2019-10-16 23:05:03

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']