本节主要内容:
python创建与删除临时文件夹。
1,python创建文件夹 代码示例:
import tempfile, os
tempfd, tempname = tempfile.mkstemp('.suffix')
os.write(tempfd, "aString") # or, if you want a file-object: os.fdopen(tempfd, 'w+')
os.close(tempfd)
os.unlink(tempname)
2,Python 删除指定文件夹中的文件 代码示例:
import win32con, win32api,shutil,os
def removePath(destinationPath):
'''
@summary: 删掉destinationPath目录,当然包括其中的子目录和文件
@param destinationPath: 所给目标目录
'''
if os.path.exists(destinationPath):
pathList = os.listdir(destinationPath)
for path in pathList: # www.#
pathFull = os.path.join(destinationPath,path)
if os.path.isfile(pathFull):
win32api.SetFileAttributes(pathFull, win32con.FILE_ATTRIBUTE_NORMAL)#to be able to delete the file we need to set it back to normal:
if os.path.isdir(pathFull):#if pathful is a dir, then call removePath function
removePath(pathFull)
shutil.rmtree(destinationPath,True)#use rmtree to remove the whole path tree
if __name__ == '__main__':
path = r'C:\Users\Administrator\AppData\Local\Temp'#删除临时文件夹中的文件
removePath(path)