Python3 os.rename() Method

Python3 OS 文件/目录方法Python3 OS File/Directory Methods


Overview

The os.rename() method is used to rename a file or directory from src to dst. If dst is an existing directory, an OSError will be raised.

Syntax

rename()The method syntax is as follows:

os.rename(src, dst)

Parameters

  • src-- The name of the directory to be modified

  • dst-- The directory name after modification

Return Value

This method has no return value.

Example

The following example demonstrates the use of the rename() method:

#!/usr/bin/python3

import os, sys

# 列出目录
print ("目录为: %s"%os.listdir(os.getcwd()))

# 重命名
os.rename("test","test2")

print ("重命名成功。")

# 列出重命名后的目录
print ("目录为: %s" %os.listdir(os.getcwd()))

The output of the above program is:

目录为:
[  'a1.txt','resume.doc','a3.py','test' ]
重命名成功。
[  'a1.txt','resume.doc','a3.py','test2' ]

Python3 OS 文件/目录方法Python3 OS File/Directory Methods

Other Extensions