Python os.rename() Method

Python File(文件) 方法Python 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 file or directory name to be modified

  • dst-- The file or directory name after modification

Return Value

This method has no return value.

Examples

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

Python File(文件) 方法Python OS File/Directory Methods

Other Extensions