Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scan files recursively and delete empty directories in python

I have the following structure:

Dir 1
|___Dir 2
   |___file 1
   |___file 2...
Dir 3
|___Dir 4
   |___file 3...

I would like to be able to find each file recursively, process the file in my own way, once done, delete the file, move to the next. Then if the directory is empty, delete that as as well, working my way up until nothing is left.

Just no sure how to proceed.

This is what I have:

for root, dirs, files in os.walk(dir):
    path = root.split('/')
    for file in files:
        file = os.path.join(root, file)
        process_file(file)
        os.remove(file)

Which is fine, but I would like then to delete the subdirs if and only they are empty.

like image 471
Joe Lones Avatar asked Feb 24 '14 23:02

Joe Lones


1 Answers

Well, I guess this will do, have to run os.walk though...

def get_files(src_dir):
# traverse root directory, and list directories as dirs and files as files
    for root, dirs, files in os.walk(src_dir):
        path = root.split('/')
        for file in files:
            process(os.path.join(root, file))
                    os.remove(os.path.join(root, file))

def del_dirs(src_dir):
    for dirpath, _, _ in os.walk(src_dir, topdown=False):  # Listing the files
        if dirpath == src_dir:
            break
        try:
            os.rmdir(dirpath)
        except OSError as ex:
            print(ex)


def main():
    get_files(src_dir)
    del_dirs(src_dir)


if __name__ == "__main__":
    main()
like image 153
Joe Lones Avatar answered Oct 03 '22 23:10

Joe Lones