Latest web development tutorials

Python3 os.rename () method

Python3 OS file / directory methods Python3 OS file / directory methods


Outline

os.rename () method is used to rename a file or directory from src to dst, dst is if an existing directory, will throw OSError.

grammar

rename () method syntax is as follows:

os.rename(src, dst)

parameter

  • src - To modify the directory name

  • dst - the modified directory name

return value

This method does not return value

Examples

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

#!/usr/bin/python3

import os, sys

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

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

print ("重命名成功。")

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

The above program output is:

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

Python3 OS file / directory methods Python3 OS file / directory methods