python 怎么删除文件

如题所述

1、创建python文件,testremove.py;

2、编写python代码,删除E:/test目录下的aaa.txt文件,

import os, sys

dirPath = "E:/test/"

print('移除前test目录下有文件:%s' %os.listdir(dirPath))

#判断文件是否存在

if(os.path.exists(dirPath+"aaa.txt")):

   os.remove(dirPath+"aaa.txt")

   print ('移除后test 目录下有文件:%s' %os.listdir(dirPath))

else:

   print ("要删除的文件不存在!")

3、右键选择‘在终端中运行Python文件’;

4、执行后查看执行结果,可以发现aaa.txt文件已经被删除,只剩下bbb.txt文件。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-27

使用os包的remove方法可以删除文件

import os
filename = 'f:/123.txt'
if os.path.exist(filename):
  os.remove(filename)

第2个回答  推荐于2017-09-21
file = 'c:/test.txt'
if os.path.exists(file):
os.remove(file)

else:
print 'no such file:%s' % file本回答被提问者和网友采纳