Home > OS >  Deleting all files in folders except for defined name in list with Python
Deleting all files in folders except for defined name in list with Python

Time:12-03

I have some folders with many files inside (they filename has all the same pattern). For example 0_ABC, 1_ABC, ..., N_ABC

I have created a list with filenames I want to keep

filename = ['65_ABC', '90_ABC', etc.]

Now I want to write a function which iterates through all files within a folder and delete everything except those names which are in the list.

How can I achieve that?

I found out how to delete files with this function but not sure what to insert in glob()

import glob, os
for f in glob.glob():
    os.remove(f)

CodePudding user response:

You can use pathlib module:

from pathlib import Path

root = Path('your/dirpath')
filenames = ['65_ABC', '90_ABC', 'etc.']

for path in root.iterdir():
    if path.name not in filenames:
        path.unlink()

This solution assumes that tour root dir contains only files. Otherwise, you can use Path.glob(pattern) to walk recursively into your directory (you should maybe also check if your path is file or dir path, with Path.is_dir() and Path.is_file()functions).

See pathlib doc to further help

  • Related