Python os.remove() 删除文件

时间:2021-10-19 14:42:23

概述

os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError

在Unix, Windows中有效

语法

remove()方法语法格式如下:

os.remove(path)

参数

  • path -- 要移除的文件路径

返回值

该方法没有返回值

实例

以下实例演示了 remove() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*- import os, sys
dirPath = "test/"
print '移除前test目录下有文件:%s' %os.listdir(dirPath)
#判断文件是否存在
if(os.path.exists(dirPath+"foo.txt")):
  os.remove(dirPath+"foo.txt")
  print '移除后test 目录下有文件:%s' %os.listdir(dirPath)
else:
  print "要删除的文件不存在!"

  

执行以上程序输出结果为:

Python os.remove() 删除文件