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 ('...
python 怎么删除文件
file = 'c:/test.txt'
if os.path.exists(file):
os.remove(file)

else:
print 'no such file:%s' % file2014-11-03
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文件。

2020-01-04
使用os包的remove方法可以删除文件
import osfilename = 'f:/123.txt'if os.path.exist(filename): os.remove(filename)2015-06-19
mengvlog 阅读 8 次 更新于 2025-07-20 04:17:28 我来答关注问题0
檬味博客在线解答立即免费咨询

Python相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部