python下文件的刪除以及文件目錄的清空

文件的刪除,給出路徑先判斷文件是否存在,存在則進行刪除,不存在如若也要刪除的話,會報錯,所有先要判斷一下

 os.remove(report_file)
 os.unlink(report_file) 都能夠進行文件的刪除

 

report_file = '/Users/qianjinyan/00A_PythonProject/auto_api_test/report/f4e071e8-845b-4afe-b8db-6e6c0c80a445-attachment.txt'
if os.path.exists(report_file):
    # 刪除文件,可使用以下兩種方法。
    # os.remove(report_file)
    os.unlink(report_file)
    print('file delete succeed:%s' % report_file)
else:
    print('no such file:%s' % report_file)

  

文件夾的清空,則一個命令既可以完成

import shutil
report_folder = '/Users/qianjinyan/00A_PythonProject/auto_api_test/report'
shutil.rmtree(report_folder)
os.mkdir(report_folder)

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章