Forum Archive

A simple file-automation desk clean up.

MustaphaBen
import os
import shutil


def main():
    p = os.path.abspath(os.getcwd())
    path = p+"/"
    files = os.listdir(path)
    for file in files:
        path_to_file = path+file

        type_of_file = file.split(".")
        path_to_dir = path+type_of_file[1]
        print(file, "-- type -- ",type_of_file[1])
        try:
            try:
                os.makedirs(type_of_file[1])
                shutil.move(path_to_file, path_to_dir)
                print(f"--{file}-- in {path_to_dir}")

            except:
                pass
        except:
            print(type_of_file[1]," already exists")
            pass

if __name__ == "__main__":
    main()

ccc

type_of_file = file.split(".")[-1] might be more intuitive and less error prone for filenames with multiple dots.

PEP8 encourages the avoidance of bare excepts. https://realpython.com/the-most-diabolical-python-antipattern/