Delete a file in a directory except for first file (or specific file) in Python

178 Views Asked by At

I want to delete all files in a directory except for one file in python. I used os.remove and os.system(with rm and fine), but all of them return errors.

Lets say I have a folder X and in there I have files named 1 2 3 4. alongside folder X, I have main.py. in main.py how can I write a command to go to the folder and delete all files except for 1.

Thanks...

I tried

os.system(f"rm -v !('1')")

but it says ''rm' is not recognized as an internal or external command, operable program or batch file.'

I tried

os.system(f"find ./X -not -name '1' -delete")
os.system(f"find /X -not -name '1' -delete")
os.system(f"find . -not -name '1' -delete")
os.system(f"find X -not -name '1' -delete")

But all of them says 'Parameter format not correct'

1

There are 1 best solutions below

0
SIGHUP On BEST ANSWER

You can do this in Python using various functions from the os module rather than relying on find.

from os import chdir, listdir, remove, getcwd

def delete_from(directory: str, keep: list) -> None:
    cwd = getcwd()
    try:
        chdir(directory)
        for file in listdir():
            if not file in keep:
                remove(file)
    finally:
        chdir(cwd)

Call this with a path to the directory to be affected and a list of files (basenames only) to be retained.

e.g.,

delete_from('X', ['1'])