当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python 3 os.renames()用法及代码示例



描述

方法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.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'python2'
]

Successfully renamed.

The dir is:[
   'Applicationdocs.docx', 'book.zip', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'newdir', 'python2'
]

结果

文件foo.txt此处不可见,因为它已移至newdir并重命名为foonew.txt.目录newdir其内容如下所示:

The dir is:['foonew.txt']

相关用法


注:本文由纯净天空筛选整理自 Python 3 - os.renames() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。