Python os.remove()方法

Python的remove()方法删除文件路径。如果路径是一个目录,则引发错误:OSError

语法

以下是remove()方法的语法 -

os.remove(path)

参数

  • path - 这是要删除的路径。

返回值

  • 此方法不返回任何值。

示例

以下示例显示了remove()方法的用法。

# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))

# removing
os.remove("test.java")

# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))

编译并运行上面的程序,将输出以下结果 -

The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer', 'test.java'
]
The dir after removal of path : [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer'
]

上一篇: Python os模块方法 下一篇: Python异常处理