1,删除文件
删除文件需要用到os模块的remove方法
1 2 3 4 5 6 7 8 9 10 11 |
#FileName:lean001.py #author:www.py40.com #删除文件 import os pathname = r'E:\\t.txt' if os.path.exists(pathname): os.remove(pathname) print('文件删除成功') else: print('文件不存在') |
注意:如果没有加文件是否存在的判断,如果文件不存在会抛出异常
1 2 3 4 5 |
>>> import os >>> os.remove(r'E:\\t.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'E:\\\\t.txt' |
2,删除文件夹
删除文件夹需要用到shutil的rmtree方法
1 2 3 4 5 6 7 8 9 10 11 |
#FileName:lean001.py #author:www.py40.com #删除文件夹 import shutil # 如果文件夹不存在会抛出异常 # shutil.rmtree(r'E://tt'); #该方法第二个参数表示忽略异常 shutil.rmtree(r'E://tt',True); |
注意:如果文件不存在,不处理则会抛出异常
1 2 3 4 5 6 7 8 9 10 11 |
>>> import shutil >>> shutil.rmtree(r'E:/11') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "E:\python\python\lib\shutil.py", line 488, in rmtree return _rmtree_unsafe(path, onerror) File "E:\python\python\lib\shutil.py", line 370, in _rmtree_unsafe onerror(os.listdir, path, sys.exc_info()) File "E:\python\python\lib\shutil.py", line 368, in _rmtree_unsafe names = os.listdir(path) FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'E:/11' |
未经允许不得转载:Python在线学习 » Python怎么删除文件和文件夹