I was writing a script to recursively delete files inside a given folder because sometimes what happens is, because of a long path name (longer than what windows supports), windows throws a "Source Path Too Long" error.
To resolve this, I have to find out which path is causing the problem and rename the folders in the path before deleting it. For example - files like these don't delete without renaming -
E:\Projects[projectName]\node_modules\babel-preset-stage-2\node_modules\babel-preset-stage-3\node_modules\babel-plugin-transform-async-to-generator\node_modules\babel-helper-remap-async-to-generator\node_modules\babel-traverse\node_modules\lodash_realNames.js
This is just one example of node installing dependencies inside dependencies.
My script was to delete cases like these, but unfortunately, python throws an error -
Unexpected error: (< type 'exceptions.WindowsError'>, WindowsError(3, 'The system cannot find the path specified'), < traceback object at 0x0000000002714F88>)
I'm guessing it truncates paths that are too long and tries to delete them. Here's my script -
import os
import sys
def delete_dir(dir_name):
for item in os.listdir(dir_name):
try:
inner_path = os.path.join(dir_name, item)
if os.path.isdir(inner_path):
delete_dir(inner_path)
else:
os.remove(inner_path)
except:
print "Unexpected error: ", sys.exc_info()
os.rmdir(dir_name)
if len(sys.argv) <= 1:
print "Usage python script.py [path]"
for path in sys.argv[1:]:
abs_path = os.path.abspath(path)
delete_dir(abs_path)
How do I handle deleting these cases through python?