Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python os.rename() method

Python os.rename() method

Python File methods Python OS file/directory methods


Overview

The os.rename() method renames a file or directory from src to dst; if dst is an existing directory, OSError is raised.

Syntax

The **rename()** method syntax is as follows:



os.rename(src, dst)

Parameters

Return Value

This method has no return value

Example

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



#!/usr/bin/python

# -*- coding: UTF-8 -*-



import os, sys



# List directory

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



# 重命名

os.rename("test","test2")



print "重命名成功。"



# List renamed directories

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

The output of the above program is:



Directory is:

[  'a1.txt','resume.doc','a3.py','test' ]

重命名成功。

[  'a1.txt','resume.doc','a3.py','test2' ]

Python File methods Python OS file/directory methods