0

I want to find top-level folders that have only digits in names. F.e. we have such folder structure

.
├── Folder1
|   ├── some.file
├── 111
|   ├── some.folder
|   ├── some.file
|   ├── some.file
|   ├── some.file-2
├── 555
|   ├── some.folder
|   ├── some.file

Expected results: found folders '111' and '555'

Here is my code:

import os

main_path = 'C:\\Users'
top_folders_list = next(os.walk(main_path))[1]
condition = '111'
if condition in top_folders_list:
   ...do_something...

Code works but (of cource) only for folder '111'. Which condition should I use for matching '111', '555' and all other top-level folders that have only digits in names?

  • 3
    Possible duplicate of [How do you check in python whether a string contains only numbers?](https://stackoverflow.com/questions/21388541/how-do-you-check-in-python-whether-a-string-contains-only-numbers) – Sayse Sep 02 '19 at 09:55
  • You can use [`str.isdecimal()`](https://docs.python.org/3/library/stdtypes.html#str.isdecimal). – Olvin Roght Sep 02 '19 at 09:59

2 Answers2

5

Use isnumeric() on string object

for fold in fold_lst:
    if fold.isnumeric():
        print(fold)  
this.srivastava
  • 1,045
  • 12
  • 22
0

You could use a regex to filter the condition:

"\d" stands for only numeric.

import re

folders = ("123451","8971231")
for folder in folders:
  x = re.findall("\\d", folder)
  result = "".join(x)
  print(result)

And that should give you the desired effect.

Community
  • 1
  • 1
  • Well, thanks. Solution above is simplier but your solution is more powerfull. F.e. for code uniformity (find not only folders with digits but also contains only letters etc) – Dmitrii Medvedev Sep 02 '19 at 10:56