-4

I am trying to create a Python script to Delete everying under C:\Windows\CSC\v2.0.6\namespace I need an Idea.. to do it in the command line i have to go to cmd an then psexec -s cmd than i have to goto C:\Windows\CSC\v2.0.6\namespace and than rd *what ever folder there.. i want to create a script to remove all.. any help

Aaron Meier
  • 929
  • 9
  • 21
Alex-
  • 125
  • 2
  • 10

2 Answers2

2

This code should delete any files or directories in your directory:

import os, shutil
folder = "C:\Windows\CSC\v2.0.6\namespace"
for item in os.listdir(folder):
    path = os.path.join(folder, item)
    try:
        os.unlink(path) # delete if the item is a file
    except Exception as e:
        shutil.rmtree(path) # delete if the item is a folder

This has been answered previously.

Community
  • 1
  • 1
Ecliptica
  • 760
  • 2
  • 8
  • 21
0

A simple Google search and a few modifications:

import os
mainPath = "C:\Windows\CSC\v2.0.6\namespace"
files = os.listdir(mainPath)
for f in files:
    os.remove('{}/{}'.format(mainPath, f))

If you want to recursively find all of the files and THEN delete them all (this is a small script I wrote yesterday):

import os, os.path
def getAllFiles(mainPath):
    subPaths = os.listdir(mainPath)
    for path in subPaths:
        pathDir = '{}\{}'.format(mainPath, path)
        if os.path.isdir(pathDir):
            paths.extend(getAllFiles(pathDir, paths))
        else:
                paths.append(pathDir)
    return paths

So then you can do:

files = getAllFiles(mainPath)
for f in files:
    os.remove(f)

Note: the recursive algorithm gets somewhat slow (and may raise a MemoryError) if there are too many subfolders (it creates a lot of recursive nodes).

To avoid this, you can use the recursive function as a helper function, which is called by a main iterative function:

def getDirs(path):
    sub = os.listdir(path)
    paths = []
    for p in sub:
        pDir = '{}\{}'.format(path, p)
        if os.path.isdir(pDir):
            paths.extend(getAllFiles(pDir, paths)) # getAllFiles is the same as above
        else:
            paths.append(pDir)
    return paths

It get's slow for very large subfolders, however. Going through C:\Python27\Lib takes about 6-7 seconds for me (it has about 5k+ files in it, and many, many subfolders).

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94