'Delete all files without deleting folders

I have a folder named (top) with 10 folders named 1,2,3,4,5,6,7,8,9, and 10.

Inside the top folder I have files, too (are not folders).

I can list all the files x = os.listdir(path).

How can I delete only the files, without deleting the folders inside the folder top?



Solution 1:[1]

The following will remove all the files in top while leaving its subfolders alone:

from pathlib import Path


for entry in Path('top').iterdir():
    if entry.is_file():
        entry.unlink()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 martineau