python创建文件夹和TXT文件,删除TXT文件和删除文件夹
需求:
1、先在D盘创建一个TEST文件夹。
2、在TEST文件夹内创建一个TXT文本文件并写入内容“Hello world!”
3、删除TEST文件夹内的TXT文件
4、删除路径TEST文件目录
import os,stat,time
dirPath = "D:\\TEST\\"
filename = "a.txt"
def createFile():
if(os.path.exists(dirPath)):
pass
print("目录"+dirPath+"已经存在")
else:
os.mkdir(dirPath)
print("创建目录"+dirPath)
file_path = dirPath + filename
print("file_path: "+ file_path)
file = open(file_path,"w+")#(w+: 开头开始编辑,如不存在则创建)
file.write("hello world!")
file.closed
file = open(file_path, "a+") # (a+: 用户追加写入)
file.write("hello world!")
file.closed
def deleteFile():
print('移除前'+dirPath+'目录下有文件:%s' %os.listdir(dirPath))
#判断文件是否存在
if(os.path.exists(dirPath + filename)):
os.remove(dirPath + filename)
print('移除后'+dirPath+'目录下有文件:%s' %os.listdir(dirPath))
else:
print("要删除的文件不存在!")
def deletePath():
if(os.path.exists(dirPath)):
os.rmdir(dirPath) # 删除目录
print('移除'+dirPath+'目录')
else:
print("要删除的路径不存在!")
print("开始执行----------------------------------------------------------------------------------------")
##注:★★如果同时创建文件并且读写后里面对其删除,那么创建和删除代码不能放一起,要拆成两个独立的方法,
## ★★否则会报【另一个程序正在使用此文件,进程无法访问】
createFile()
time.sleep(8)# 8 秒后删除TXT文件
deleteFile()
time.sleep(8)# 8 秒后删除路径TEST
deletePath()
print("结束执行----------------------------------------------------------------------------------------")
执行结果:
开始执行----------------------------------------------------------------------------------------
创建目录D:\TEST
file_path: D:\TEST\a.txt
移除前D:\TEST\目录下有文件:[‘a.txt’]
移除后D:\TEST\目录下有文件:[]
移除D:\TEST\目录
结束执行----------------------------------------------------------------------------------------