Delete files in Python
May 05, 2009 19:59:21 Last update: May 05, 2009 19:59:21
Delete a single file:
Delete a directory and contents:
>>> import os >>> file = 'myfile' >>> os.remove('hfkg/' + file) Traceback (most recent call last): File "<stdin>", line 1, in <module> WindowsError: [Error 2] The system cannot find the path specified: 'hfkg/myfile'
Delete a directory and contents:
>>> import shutil >>> dir(shutil) ['Error', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_samefi le', 'abspath', 'copy', 'copy2', 'copyfile', 'copyfileobj', 'copymode', 'copysta t', 'copytree', 'destinsrc', 'move', 'os', 'rmtree', 'stat', 'sys'] >>> shutil.rmtree('jgdl') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python25\lib\shutil.py", line 161, in rmtree onerror(os.listdir, path, sys.exc_info()) File "C:\Python25\lib\shutil.py", line 159, in rmtree names = os.listdir(path) WindowsError: [Error 2] The system cannot find the path specified: 'jgdl/*.*' >>>