Search code examples
pythonfilepython-2.7recursionremoveall

Python 2.7 - Delete all the __init__.py and __init__.pyc files recursively


I'm developing a python command-line tool, and it should delete the __init__.* files in the entire project tree. I tried this:

subprocess.call(['find', './<directory>', -name, '"__init__.*"', '-delete'])

where actually has the path...

Any ideas?

NOTE: This works using the terminal. When it comes to do it in python, however; it will not delete anything (the script continues though, it doesn't throw any errors).


Solution

  • You can try to use the glob module to remove the files under a given subdirectory:

    import glob, os
    init_files = glob.glob('./directory/__init__.*')
    for f in init_files: os.remove(f)
    

    To go through subdirectories recursively you could use the os.walk function:

    import os, fnmatch
    for root, dirs, files in os.walk('./directory'):
        for f in fnmatch.filter(files, '__init__.*'):
            os.remove(f)