[英]Python: find top-level folders that have only digits in names
I want to find top-level folders that have only digits in names. 我想查找名称中仅包含数字的顶级文件夹。 Fe 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' 预期结果:找到文件夹“ 111”和“ 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'. 代码有效,但(仅适用于)文件夹“ 111”。 Which condition should I use for matching '111', '555' and all other top-level folders that have only digits in names? 我应该使用哪种条件来匹配“ 111”,“ 555”以及名称中只有数字的所有其他顶级文件夹?
Use isnumeric()
on string object 在字符串对象上使用isnumeric()
for fold in fold_lst:
if fold.isnumeric():
print(fold)
You could use a regex to filter the condition: 您可以使用正则表达式来过滤条件:
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. 那应该给您想要的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.