Python os.rename() method
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
-
src -- the name of the file or directory to change
-
dst -- the new name of the file or directory
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' ]