0

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?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Zeokav
  • 1,653
  • 4
  • 14
  • 29
  • 2
    Be aware that this utility already exists: [`shutil.rmtree`](https://docs.python.org/3/library/shutil.html#shutil.rmtree). It may be faster or more efficient that yours. – aghast Feb 19 '17 at 07:32
  • 1
    @AustinHastings I'm aware, but I wrote this only because shutil.rmtree throws an error too. :/ – Zeokav Feb 19 '17 at 07:49
  • Too bad. I was hoping it would work for you. :( – aghast Feb 19 '17 at 15:44
  • What function is throwing the exception? Can we get a longer traceback? – aghast Feb 19 '17 at 15:45

0 Answers0