1、python判斷文件夾是否存在,不存在則創(chuàng)建它,并將文件夾下所有的文件及子文件刪除
import os
import shutil
if not os.path.exists(path):
os.mkdir(path)
if os.listdir(save_path):
file_list = os.listdir(save_path)
for f in file_list:
file_path = os.path.join(save_path, f)
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path, True)
2、python之判斷文件&文件夾是否存在,存在則刪除,不存在則創(chuàng)建
2.1、刪除文件于文件夾
import os
if os.path.exists(r'c:\test.xlsx'):
os.remove(r'c:\test.xlsx')
使用os.remove刪除文件夾會(huì)出現(xiàn)拒絕訪問的錯(cuò)誤,所以要使用以下方式進(jìn)行刪除
import os
import shutil
if os.path.exists(r'c:\1'):
shutil.rmtree(r'c:\1')
2.2、創(chuàng)建文件與文件夾
創(chuàng)建文件文章來源:http://www.zghlxwxcb.cn/news/detail-505432.html
import os
current_path = os.getcwd() #獲取當(dāng)前路徑
print(current_path)
path = current_path+'\\test.txt' #在當(dāng)前路徑創(chuàng)建名為test的文本文件
if os.path.exists(path):
print('exist')
else:
os.mkdir(path)
創(chuàng)建文件夾文章來源地址http://www.zghlxwxcb.cn/news/detail-505432.html
import os
current_path = os.getcwd() #獲取當(dāng)前路徑
path = current_path+'\\test' #在當(dāng)前路徑創(chuàng)建名為test的文件夾
if os.path.exists(path):
print('exist')
else:
os.mkdir(path) #創(chuàng)建
到了這里,關(guān)于python判斷文件夾是否存在,不存在則創(chuàng)建它,并將文件夾下所有的文件及子文件刪除的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!