Utility to remove all files you do not need in subfolders

This is an utility that I needed to clean a directory of all the mp4 files and the ts (temporary) files I make to do video tutorials. So I made this live coding metacognitive kinda tutorial to share with you how to do it. I figured out how to do it live, so it is a bit long. You find the code down here and the video also below. Thanks and see you next time.

Thing you will get in this code:

  • os.listdir()
  • os.path.isfile(filename)
  • os.path.isdir(filename)
  • shutil (but unused)
  • shutil.rmtree (unused at the end)
  • os.remove(file)
  • os.rmdir()
  • os.getcwd()

and other interesting stuffs.

#delete all mp4 files in the dir
import os
import glob
import shutil


def delete_all():
    print("Delete all mp4 in the folders? " + os.getcwd())
    ask = input("(y/n)>: ")
    if ask == "y":
        folders = [x for x in os.listdir(".") if os.path.isdir(x)]
        print("folders", folders)
        for f in folders:
            files = [x for x in os.listdir(f) if x.endswith(".mp4")]
            tsfiles = [x for x in os.listdir(f) if x.endswith(".ts")]
            print(files)
            if files != []:
                for file in files:
                    os.remove(f + "\\" + file)
                    print("removing: ", file)
            for ts in tsfiles:
                os.remove(f + "\\" + ts)
                print("removing: ", file)
        empty = [fol for fol in folders if os.listdir(fol) == []]
        print("empty", empty)
        for folder in empty:
            os.rmdir(folder)
            print("Removed empty folder:", folder)

    #look_for_mp4()


def look_for_mp4():
    for f in os.listdir():
        if not os.path.isfile(f):
            print(f)
            print(os.listdir(f))
            print("=======\n")

delete_all()

The live coding video

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.