【问题标题】:Python: find top-level folders that have only digits in namesPython:查找名称中只有数字的顶级文件夹
【发布时间】:2019-09-02 09:53:47
【问题描述】:

我想查找名称中只有数字的顶级文件夹。 F.e.我们有这样的文件夹结构

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

预期结果:找到文件夹“111”和“555”

这是我的代码:

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...

代码有效,但(当然)仅适用于文件夹“111”。我应该使用哪个条件来匹配“111”、“555”和所有其他名称中只有数字的顶级文件夹?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

在字符串对象上使用isnumeric()

for fold in fold_lst:
    if fold.isnumeric():
        print(fold)  

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来过滤条件:

    “\d”只代表数字。

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

    这应该会给你想要的效果。

    【讨论】:

    • 好的,谢谢。上面的解决方案更简单,但您的解决方案更强大。 F.e.为了代码一致性(不仅找到带有数字的文件夹,而且只包含字母等)
    猜你喜欢
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2021-10-30
    • 1970-01-01
    • 2015-08-12
    • 2015-03-18
    • 2015-10-17
    相关资源
    最近更新 更多